Java programming unite 8
Java programming unite 8
Source code:
MainApp.java
import javax.swing.*;
WeatherAPI.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed to get weather data: " +
conn.getResponseCode());
}
return parseWeatherData(response.toString());
}
try {
// Extract temperature
int tempIndex = response.indexOf("\"temp\":");
if (tempIndex != -1) {
String tempStr = response.substring(tempIndex + 7);
tempStr = tempStr.split(",")[0]; // Get the first value
after "temp"
weatherData.setTemperature(Double.parseDouble(tempStr));
}
// Extract humidity
int humidityIndex = response.indexOf("\"humidity\":");
if (humidityIndex != -1) {
String humidityStr = response.substring(humidityIndex +
11);
humidityStr = humidityStr.split(",")[0]; // Get the first
value after "humidity"
weatherData.setHumidity(Double.parseDouble(humidityStr));
}
weatherData.setWindSpeed(Double.parseDouble(windSpeedStr));
}
return weatherData;
}
}
WeatherAppGUI.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
public WeatherAppGUI() {
// Initialize the weather API with your API key
weatherAPI = new WeatherAPI("460a616923ee53bc6e7268a0324e9b08");
// Replace with your API key
history = new ArrayList<>();
// Input panel
JPanel inputPanel = new JPanel();
locationField = new JTextField(15);
JButton searchButton = new JButton("Get Weather");
unitComboBox = new JComboBox<>(new String[]{"Celsius",
"Fahrenheit"});
WeatherData.java
public class WeatherData {
private double temperature;
private double humidity;
private double windSpeed;
private String conditions;