Search code examples
javavariablesjoptionpaneinitializing

Error message when trying to use .equals to give a value to a variable


I want to add up the values of temperature, humidity, and sunshine, but I don't know why it says that the "sunshine" variable isn't declared. I want it to work so that when the user types in "yes", then sunshine gets set to 25, and if they type no, it gets set to -25. Thanks!

  int temperature;
  double humidity;
  int sunshine;
  String temp;
  double rating;

temp = JOptionPane.showInputDialog(null, "What temperature is it outside?");
temperature = Integer.parseInt(temp);
temp = JOptionPane.showInputDialog(null, "What percentage of humidity is there?");
humidity = Double.parseDouble(temp);
temp = JOptionPane.showInputDialog(null, "Is it cloudy out?");
if (temp.equals("yes"))
  sunshine = 25;
if (temp.equals("no"))
  sunshine = -25;

rating = temperature + humidity + sunshine;

Solution

  • You haven't told the user to type "yes" or "no" to the sunshine question and you're not checking to make sure the user typed either value. If I don't type either "yes" or "no", then the sunshine variable is being used before any value is assigned to it.

    You can eliminate the symptom with

    int sunshine = 0;
    

    but that doesn't cure the problem.

    You should:

    1) Instruct the user to type either "yes" or "no".

    2) Check that the user typed either "yes" or "no" and ask the question until a correct value is typed in

    3) For better form, use an if/else statement.

    Here's a new code snippet:

    temp = JOptionPane.showInputDialog(null, "What temperature is it outside?");
    temperature = Integer.parseInt(temp);
    temp = JOptionPane.showInputDialog(null, "What percentage of humidity is there?");
    humidity = Double.parseDouble(temp);
    temp = "";
    while (!temp.equals("yes") && !temp.equals("no")) {
       temp = JOptionPane.showInputDialog(null, "Is it cloudy out? Type 'yes' or 'no' ");
    }
    if (temp.equals("yes"))
      sunshine = 25;
    else
      sunshine = -25;
    
    rating = temperature + humidity + sunshine;