Exercise: Fetch Weather Data and Write to a File


Due Date 6/19 11:59 PM

Objective:

Use the OpenWeatherMap API to fetch weather data for a city based on its ZIP code and write the weather data to a file.

Steps:

  1. Create an account with openweathermap.org and get the API key.
  2. Use the following API endpoint: API request by ZIP code.
  3. Fetch weather data from the OpenWeatherMap API using the ZIP code.
  4. Ask the user to input a 5-digit ZIP code.
  5. Create two Java methods to read and write. Call the methods from the main class.
  6. Write the weather data to a file as a weather_data.json file.

Java Code:

          
public class WeatherDataExercise {
    public static void main(String[] args) {
        // OpenWeatherMap API key (replace with your own API key)
        String apiKey = "";

        // Step 1: Ask the user for a 5-digit ZIP code
        // Step 2: Fetch weather data from the API
            String apiUrl = "https://api.openweathermap.org/data/2.5/weather?zip=" "
        
            // Step 3: Write the weather data to a file
        
            // Step 4: Read back the JSON file and display its content
        
    }
}
          
        

Expected Output:

Enter a 5-digit ZIP code: 21114
Weather data written to file successfully!

Reading back the JSON file...
Contents of weather_data.json:
{
    "coord": {
      "lon": -76.6802,
      "lat": 39.0112
    },
    "weather": [
      {
        "id": 800,
        "main": "Clear",
        "description": "clear sky",
        "icon": "01d"
      }
    ],
    "base": "stations",
    "main": {
      "temp": 278.41,
      "feels_like": 275.9,
      "temp_min": 277.46,
      "temp_max": 279.71,
      "pressure": 1024,
      "humidity": 42,
      "sea_level": 1024,
      "grnd_level": 1019
    },
    "visibility": 10000,
    "wind": {
      "speed": 3.09,
      "deg": 280
    },
    "clouds": {
      "all": 0
    },
    "dt": 1740325720,
    "sys": {
      "type": 2,
      "id": 2002307,
      "country": "US",
      "sunrise": 1740311258,
      "sunset": 1740351168
    },
    "timezone": -18000,
    "id": 0,
    "name": "Crofton",
    "cod": 200
  }

How to Submit Assignment?

  • Add your full name and email at the top of the file using a comment tag.
  • Compile and run your program, entering the required inputs.
  • Take a screenshot of the result and upload it on Blackboard.
  • Zip your project with the source code, then upload it on Blackboard.