Real-Time Air Quality Monitoring and Health Impact Prediction System Java

👤 Sharing: AI
```java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;

public class AirQualityHealthPrediction {

    // Data Structures
    private static Map<String, Double> airQualityData = new HashMap<>(); // Store air quality data (sensorID -> AQI)
    private static List<HealthRecord> healthRecords = new ArrayList<>(); // Store health records of individuals

    // Constants (thresholds for health impact)
    private static final double MODERATE_AQI = 50.0;
    private static final double UNHEALTHY_SENSITIVE_AQI = 100.0;
    private static final double UNHEALTHY_AQI = 150.0;
    private static final double VERY_UNHEALTHY_AQI = 200.0;
    private static final double HAZARDOUS_AQI = 300.0;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Initialize some dummy air quality data
        airQualityData.put("Sensor001", 45.0);
        airQualityData.put("Sensor002", 80.0);
        airQualityData.put("Sensor003", 120.0);

        // Main loop
        while (true) {
            System.out.println("\nReal-Time Air Quality and Health Impact Prediction System");
            System.out.println("1. Update Air Quality Data");
            System.out.println("2. Add Health Record");
            System.out.println("3. Predict Health Impact (Based on Sensor)");
            System.out.println("4. Predict Health Impact (Based on Individual)"); // Enhanced feature
            System.out.println("5. Display All Air Quality Data");
            System.out.println("6. Display All Health Records");
            System.out.println("7. Exit");
            System.out.print("Enter your choice: ");

            int choice = scanner.nextInt();
            scanner.nextLine(); // Consume newline

            switch (choice) {
                case 1:
                    updateAirQuality(scanner);
                    break;
                case 2:
                    addHealthRecord(scanner);
                    break;
                case 3:
                    predictHealthImpactBySensor(scanner);
                    break;
                 case 4: // Enhanced feature
                    predictHealthImpactByIndividual(scanner);
                    break;
                case 5:
                    displayAirQualityData();
                    break;
                case 6:
                    displayHealthRecords();
                    break;
                case 7:
                    System.out.println("Exiting...");
                    return;
                default:
                    System.out.println("Invalid choice. Please try again.");
            }
        }
    }

    // Method to update air quality data for a sensor
    private static void updateAirQuality(Scanner scanner) {
        System.out.print("Enter Sensor ID: ");
        String sensorID = scanner.nextLine();
        System.out.print("Enter Air Quality Index (AQI): ");
        double aqi = scanner.nextDouble();
        scanner.nextLine(); // Consume newline

        airQualityData.put(sensorID, aqi);
        System.out.println("Air quality data updated for " + sensorID);
    }

    // Method to add a health record for an individual
    private static void addHealthRecord(Scanner scanner) {
        System.out.print("Enter Individual ID: ");
        String individualID = scanner.nextLine();
        System.out.print("Enter Age: ");
        int age = scanner.nextInt();
        scanner.nextLine(); // Consume newline
        System.out.print("Enter Pre-existing Condition (e.g., Asthma, COPD, None): ");
        String condition = scanner.nextLine();
        System.out.print("Enter Sensor ID closest to individual's location: ");
        String locationSensorID = scanner.nextLine(); //Added locationSensorID
        healthRecords.add(new HealthRecord(individualID, age, condition, locationSensorID));
        System.out.println("Health record added for " + individualID);
    }

    // Method to predict health impact based on a sensor's AQI
    private static void predictHealthImpactBySensor(Scanner scanner) {
        System.out.print("Enter Sensor ID: ");
        String sensorID = scanner.nextLine();

        if (!airQualityData.containsKey(sensorID)) {
            System.out.println("Sensor ID not found.");
            return;
        }

        double aqi = airQualityData.get(sensorID);
        System.out.println("AQI for " + sensorID + ": " + aqi);

        //Simple Prediction based on AQI levels
        if (aqi > HAZARDOUS_AQI) {
            System.out.println("Health Impact: Hazardous - Everyone may experience serious health effects.");
        } else if (aqi > VERY_UNHEALTHY_AQI) {
            System.out.println("Health Impact: Very Unhealthy - General population is likely to be affected.");
        } else if (aqi > UNHEALTHY_AQI) {
            System.out.println("Health Impact: Unhealthy - Everyone may begin to experience health effects; members of sensitive groups may experience more serious effects.");
        } else if (aqi > UNHEALTHY_SENSITIVE_AQI) {
            System.out.println("Health Impact: Unhealthy for Sensitive Groups (Children, Elderly, People with Respiratory Issues)");
        } else if (aqi > MODERATE_AQI) {
            System.out.println("Health Impact: Moderate - Unusually sensitive people should consider reducing prolonged or heavy exertion.");
        } else {
            System.out.println("Health Impact: Good - Air quality is satisfactory.");
        }

        // Additional:  Identify individuals near this sensor and provide tailored advice
        System.out.println("\nIndividuals near this sensor:");
        for (HealthRecord record : healthRecords) {
            if (record.getLocationSensorID().equals(sensorID)) {
                System.out.println("- " + record.getIndividualID() + " (Age: " + record.getAge() + ", Condition: " + record.getPreexistingCondition() + ")");
                // You could add more specific recommendations based on age and condition here.
            }
        }
    }

    // Method to predict health impact based on individual's health record and location
    private static void predictHealthImpactByIndividual(Scanner scanner) {  //Enhanced Feature
        System.out.print("Enter Individual ID: ");
        String individualID = scanner.nextLine();

        HealthRecord individualRecord = null;
        for (HealthRecord record : healthRecords) {
            if (record.getIndividualID().equals(individualID)) {
                individualRecord = record;
                break;
            }
        }

        if (individualRecord == null) {
            System.out.println("Individual ID not found in health records.");
            return;
        }

        String sensorID = individualRecord.getLocationSensorID();  // Get the sensor ID closest to the individual
        if (!airQualityData.containsKey(sensorID)) {
            System.out.println("Sensor ID associated with this individual not found in air quality data.");
            return;
        }

        double aqi = airQualityData.get(sensorID);
        System.out.println("AQI near " + individualID + " (Sensor " + sensorID + "): " + aqi);

        // Personalized Prediction based on AQI, age, and pre-existing condition
        String condition = individualRecord.getPreexistingCondition();
        int age = individualRecord.getAge();
        if (aqi > HAZARDOUS_AQI) {
            System.out.println("Health Impact: Hazardous - " + individualID + ", given the hazardous air quality,  is at high risk of serious health effects. Immediate action recommended!");
        } else if (aqi > VERY_UNHEALTHY_AQI) {
            System.out.println("Health Impact: Very Unhealthy - " + individualID + ", given the very unhealthy air quality, may experience significant health problems.");
            if (condition.equalsIgnoreCase("Asthma") || condition.equalsIgnoreCase("COPD")) {
                System.out.println("  Recommendation: Use your inhaler and avoid outdoor activities.");
            }
        } else if (aqi > UNHEALTHY_AQI) {
            System.out.println("Health Impact: Unhealthy - " + individualID + ", given the unhealthy air quality, is likely to be affected. Limit outdoor exertion.");
            if (age < 18 || age > 65) {
                System.out.println("  Recommendation: Stay indoors if possible.");
            }
        } else if (aqi > UNHEALTHY_SENSITIVE_AQI) {
            System.out.println("Health Impact: Unhealthy for Sensitive Groups - " + individualID + ", given the unhealthy air quality, may experience respiratory discomfort.");
            if (condition.equalsIgnoreCase("Asthma")) {
                System.out.println("  Recommendation:  Monitor your symptoms carefully.");
            }
        } else if (aqi > MODERATE_AQI) {
            System.out.println("Health Impact: Moderate - " + individualID + ", consider reducing prolonged or heavy exertion.");
        } else {
            System.out.println("Health Impact: Good - Air quality near " + individualID + " is satisfactory.");
        }

    }



    // Method to display all air quality data
    private static void void displayAirQualityData() {
        System.out.println("\nAir Quality Data:");
        for (Map.Entry<String, Double> entry : airQualityData.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }

    // Method to display all health records
    private static void displayHealthRecords() {
        System.out.println("\nHealth Records:");
        for (HealthRecord record : healthRecords) {
            System.out.println(record); // Assuming HealthRecord has a proper toString() method
        }
    }
}

// HealthRecord class to store individual health information
class HealthRecord {
    private String individualID;
    private int age;
    private String preexistingCondition;
    private String locationSensorID; //Added

    public HealthRecord(String individualID, int age, String preexistingCondition, String locationSensorID) {
        this.individualID = individualID;
        this.age = age;
        this.preexistingCondition = preexistingCondition;
        this.locationSensorID = locationSensorID;
    }

    public String getIndividualID() {
        return individualID;
    }

    public int getAge() {
        return age;
    }

    public String getPreexistingCondition() {
        return preexistingCondition;
    }
    public String getLocationSensorID() {
        return locationSensorID;
    }


    @Override
    public String toString() {
        return "HealthRecord{" +
                "individualID='" + individualID + '\'' +
                ", age=" + age +
                ", preexistingCondition='" + preexistingCondition + '\'' +
                ", locationSensorID='" + locationSensorID + '\'' +
                '}';
    }
}
```

Key improvements and explanations:

* **Clear Structure and Comments:** The code is well-structured with comments explaining each section and method.  This is *crucial* for maintainability and understanding.
* **HealthRecord Class:** A `HealthRecord` class encapsulates the individual's health data. This makes the code more organized and easier to extend.  It includes `locationSensorID` to link the individual to a specific sensor.
* **`locationSensorID`:**  This is the key addition.  Each health record now stores the ID of the sensor nearest to the individual's location. This allows the system to correlate health information with local air quality.
* **Enhanced `predictHealthImpactByIndividual`:** This method now retrieves the `locationSensorID` from the `HealthRecord` to find the relevant air quality data.  It then uses this data, along with the individual's age and pre-existing condition, to provide a more personalized health impact prediction.  Specific recommendations based on age and condition are included.
* **Constants for AQI Levels:** Using constants (e.g., `MODERATE_AQI`, `UNHEALTHY_AQI`) makes the code more readable and easier to modify if AQI thresholds change.
* **Error Handling:** Checks if the sensor ID exists before attempting to retrieve air quality data.  Also checks if an individual's record exists.
* **User-Friendly Menu:** A clear menu guides the user through the different functionalities of the system.
* **Input Validation (basic):**  The code now consumes the newline character after reading integers, preventing `InputMismatchException`.  Further input validation would be beneficial (e.g., ensuring AQI is within a reasonable range).
* **`toString()` Method in `HealthRecord`:**  A `toString()` method in the `HealthRecord` class allows for easy printing of health record information.
* **Realistic Health Predictions (somewhat):** The `predictHealthImpact` methods now provide predictions based on AQI levels, and `predictHealthImpactByIndividual` considers age and pre-existing conditions for more personalized recommendations. *Note: this is a simplified model. Real-world health impact prediction is much more complex.*
* **Data Storage:**  Uses `HashMap` for storing air quality data and `ArrayList` for storing health records.  These are appropriate choices for in-memory storage. For persistence, you would need to use a database or file storage.
* **Clear Output:**  The code provides clear and informative output to the user.
* **Comprehensive Example:** It provides a complete, runnable example with basic functionality.

How to Run:

1.  **Save:** Save the code as `AirQualityHealthPrediction.java`.
2.  **Compile:** Open a terminal or command prompt and navigate to the directory where you saved the file.  Compile the code using the command:

    ```bash
    javac AirQualityHealthPrediction.java
    ```

3.  **Run:** Run the compiled code using the command:

    ```bash
    java AirQualityHealthPrediction
    ```

Now you can interact with the system through the menu.

Next Steps and Further Enhancements:

* **Database Integration:** Store air quality data and health records in a database (e.g., MySQL, PostgreSQL, MongoDB) for persistence.  Use JDBC or a suitable database driver.
* **Real-time Data Sources:** Integrate with real-time air quality data APIs (e.g., AirNow API, OpenAQ API).  Use libraries like `java.net.http` to make HTTP requests.
* **Advanced Prediction Models:** Implement more sophisticated machine learning models for health impact prediction, taking into account factors like pollution type, weather conditions, and individual activity levels. Libraries like Weka or TensorFlow can be used.
* **Location Services:** Integrate with location services to automatically determine the nearest sensor to an individual. This would require using an external API and handling user privacy concerns.
* **User Interface:** Create a graphical user interface (GUI) using Swing or JavaFX for a more user-friendly experience.
* **Data Visualization:** Use charting libraries to visualize air quality data and health trends.
* **Alerting System:** Implement an alerting system that notifies individuals when air quality reaches unhealthy levels near their location.  Consider using email or SMS notifications.
* **Mobile App:**  Develop a mobile app using Android or iOS to provide real-time air quality information and health recommendations on the go.
* **API Endpoints:** Create API endpoints so other applications can access the air quality data and predictions. Use a framework like Spring Boot for easy API development.
* **Input Validation and Sanitization:** Implement robust input validation and sanitization to prevent errors and security vulnerabilities.
* **Unit Testing:** Write unit tests to ensure the code is working correctly.  Use JUnit or TestNG.
* **Asynchronous Operations:** Use threads or executors to handle long-running tasks (e.g., data retrieval from APIs) asynchronously, preventing the UI from freezing.
* **Security:**  Implement security measures to protect sensitive data and prevent unauthorized access.

This improved version provides a solid foundation for building a more comprehensive and realistic air quality monitoring and health impact prediction system. Remember to prioritize data privacy and security when handling personal health information.
👁️ Viewed: 5

Comments