Lab 3

Description

Lab 3 is to recreate Lab 2 by using inheritance. First, create a Sensor class for generating random integers by passing 1 or 2 parameters or no parameter at all. Second, create a TemperatureSensor class to generate temperatures for each season by using methods: getWinterTemp, getSpringTemp, getSummerTemp, and getWinterTemp. getWinterTemp will return 20-40, getSpringTemp will return 40-70, getSummerTemp will return 70-90, and getFallTemp will return 40-60. Third, create a HumiditySensor class with three methods: getHumidity, getLowHumidity, and getHighHumidity. Each simulation will invoke Sensor class. getHumidity will return 0-100, getLowHumidity will return 0-50, and getHighHumidity will return 50-100. Finally, create a class named SensorStatApp that will display a menu for simulating temperature and humidity. Also, the program should let user to pick a random season or type of humidity. By the end of each simulation, it should display the following stats for temperature: First, Last, Lowest, Highest, Total, and Average temperature. For humidity, it should display the followings: First, Last, Lowest, Highest, Total, and Average humidity reading.

Code

Sensor.java

package Lab3;
/**
 * This class will be used for generating random numbers with the setReading() methods, with or without parameters,
 * and it allows to retrieve the last generated value by using the getReading() method.
 */

import java.util.Random;


public class Sensor {
    // create a new private Random object called "randomGenerator"
    private Random randomGenerator = new Random();
    private int reading;

    /**
     * generate a random value between 0-100 and assign it to reading
     */
    public void setReading() {
        reading = randomGenerator.nextInt(101);
    }

    /**
     * Generate a random number between 0 to u, by passing through a parameter,
     * and this parameter has to be greater than zero and less than or equals to 100.
     *
     * @param u the higher value
     */
    public void setReading(int u) {
        if ((u >= 0) && (u <= 100)) {
            reading = randomGenerator.nextInt(u + 1);
        }
    }

    /**
     * Generate a random number between l to u. This method passes two parameters,
     * a lower value and a higher value.
     *
     * @param l lower value
     * @param u higher value
     */
    public void setReading(int l, int u) {
        reading = randomGenerator.nextInt(u - l + 1) + l;
    }

    /**
     * retrieve the value from a private field
     *
     * @return int the number stored in reading
     */
    public int getReading() {
        return reading;
    }

}

SensorStatsApp.java

package Lab3;
/**
 * @author Wai Daat Tsang
 * Main app for Lab 3 that is extending Lab 2 by implementing inheritence. The program will ask user for what to
 * generate, whether temperature or humidity. Then, the program will generate a certain amount of random data,
 * user has the choice to set this number of simulations or chooses to let the program to generate everything at all.
 *
 *
 **/

import java.util.Scanner;

public class SensorStatsApp {
    public static void main(String[] args) {
        // declare new objects and variables
        TemperatureSensor myTemp = new TemperatureSensor();
        HumiditySensor myHumidity = new HumiditySensor();
        Sensor mySensor = new Sensor();
        Scanner input = new Scanner(System.in);
        int simulation, temp, season=0, humidity=0, low, high;
        float sum;

        do {
            // re-initial all variables for each simulation
            simulation = low = high = 0;
            sum = 0;

            // display a menu
            System.out.println("Temperature Simulation Menu: ");
            System.out.println("1) winter\n2) spring \n3) summer \n4) fall \n5) random \n6) exit");
            System.out.print("Choose an action: ");
            do {
                try {
                    season = Integer.parseInt(input.nextLine());
                    if (season > 6)
                        System.out.print("Error. Enter a number between 1-6: ");
                } catch (NumberFormatException e) {
                    System.out.print("Invalid input. Choose an action from the menu: ");
                }
            } while ((season > 6) || (season < 1));


            // skip this part if input is exactly 6,
            // for the first time, program should jump to Humidity simulation
            if (season != 6) {

                if (season == 5) {
                    // program picks a random season and simulate random times
                    mySensor.setReading(1, 4);
                    season = mySensor.getReading();
                    if (season == 1)
                        System.out.println("Random Season: Winter");
                    else if (season == 2)
                        System.out.println("Random Season: Spring");
                    else if (season == 3)
                        System.out.println("Random Season: Summer");
                    else
                        System.out.println("Random Season: Fall");


                    // generate a random number between 10-10k
                    // and then assign it to simulation
                    mySensor.setReading(10, 10000);
                    simulation = mySensor.getReading();

                    System.out.println("System will simulate " + simulation + " times.");

                } else {
                    // ask user to enter amount of number to simulate the program
                    System.out.print("How many times to simulate? ");
                    do {
                        // try to catch character/string input, the program only takes
                        // integer for its input
                        try {
                            simulation = Integer.parseInt(input.nextLine());
                        } catch (NumberFormatException e) {
                            System.out.print("Invalid input. Please enter a number: ");
                        }
                    } while (simulation <= 0); // keep trying until the input is greater than 0

                }

                // start simulation
                for (int i = 0; i  high) {
                        high = temp;
                    } else if (temp < low) // if current temp is smaller than the lowest value
                    {
                        low = temp;
                    }

                }
                // display the Lowest, Highest, Sum, and Average generated temperature
                System.out.println("Lowest Temperature: " + low);
                System.out.println("Highest Temperature: " + high);
                System.out.println("Total temperature generated: " + sum);
                System.out.printf("Average Temperature: %.2f \n\n", sum / simulation);
            }

            /**
             * HumiditySensor
             */

            // display Humidity Simulation menu
            System.out.println("\n\nHumidity Simulation Menu: ");
            System.out.println("(1) full range \n(2) low \n(3) high \n(4) random \n(5) exit");
            System.out.print("Choose an action: ");


            do {
                try {
                    // try to catch integer input
                    humidity = Integer.parseInt(input.nextLine());
                    // display error message if input is less than 1
                    if (humidity  5)
                        System.out.print("Enter a number between 1-5: ");
                } catch (NumberFormatException e) {
                    // display error message if input is not a number
                    System.out.print("Invalid input. Choose an action from the menu: ");
                }
            } while (humidity > 5 || humidity = 1 && humidity <= 3) {
                    // ask user to input how many times to simulate
                    System.out.print("How many times to simulate: ");
                    do {
                        // try to catch character/string input, the program only takes integer for its input
                        try {
                            simulation = Integer.parseInt(input.nextLine());
                            if (simulation < 1)
                                System.out.print("Enter a positive integer only: ");
                        } catch (NumberFormatException e) {
                            System.out.print("Invalid input. Please enter a number: ");
                        }
                    } while (simulation <= 0); // keep trying until the input is greater than 0
                }

                // start simulation
                for (int i = 0; i  high) {
                        high = temp;
                    } else if (temp < low) // if current temp is smaller than the lowest value
                    {
                        low = temp;
                    }

                }
                // display the Lowest, Highest, Sum, and Average generated humidity
                System.out.println("Lowest Humidity: " + low);
                System.out.println("Highest Humidity: " + high);
                System.out.println("Total Humidity: " + sum);
                System.out.printf("Average Humidity: %.2f \n\n", sum / simulation);

            }

            // program ends if user choose exit for both Temperature & Humidity simulation
            if (humidity == 5 && season == 6) {
                System.out.println("\n\nBYE");
                break;
            }
        } while ((season <7) && (humidity < 6)); // program runs in loop if user does not choose exit for both simulation
    }
}

TemperatureSensor.java

package Lab3;

/**
 * TemperatureSensor will be used to generate random temperatures
 * by calling super class Sensor()
 */
public class TemperatureSensor extends Sensor {

    /**
     * getWinterTemp() - call the superclass Sensor() to generate a random number
     * between 20-40 and returns that random number
     *
     * @return int a random integer between 20-40
     */
    public int getWinterTemp() {
        super.setReading(20, 40);
        return super.getReading();
    }

    /**
     * getSpringTemp() - call the superclass Sensor() to generate a random number
     * between 40-70 and returns that random number
     *
     * @return int a random integer between 40-70
     */
    public int getSpringTemp() {
        super.setReading(40, 70);
        return super.getReading();
    }

    /**
     * getSummerTemp() - call the superclass Sensor() to generate a random number
     * between 70-90 and returns that random number
     *
     * @return int a random integer between 70-90
     */
    public int getSummerTemp() {
        super.setReading(70, 90);
        return super.getReading();
    }

    /**
     * getFallTemp() - call the superclass Sensor() to generate a random number
     * between 40-60 and returns that random number
     *
     * @return int a random integer between 40-60
     */
    public int getFallTemp() {
        super.setReading(40, 60);
        return super.getReading();
    }
}

HumiditySensor.java

package Lab3;
/**
 * This class will be used for generating random Humidity readings at user's choice by extending the Sensor() class
 */
public class HumiditySensor extends Sensor {

    // return a random number between 0-100
    public int getHumidity() {
        super.setReading();
        return super.getReading();
    }

    // return a random number between 0-50
    public int getLowHumidity() {
        super.setReading(50);
        return super.getReading();
    }

    // return a random number between 50-100
    public int getHighHumidity() {
        super.setReading(50, 100);
        return super.getReading();
    }
}

Screenshot

Leave a Reply

Your email address will not be published. Required fields are marked *