0

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;
  • 2
    If the temp is neither yes or no what will `sunshine` be when you get to the line `rating = temperature + humidity + sunshine;`. Change the deceleration to `int sunshine = 0;` – GBlodgett Oct 05 '18 at 00:37
  • I strongly suspect that it doesn't say that `sunshine` isn't declared - instead it's going to complain that `sunshine` isn't *definitely assigned*. You're not assigning a value to it if `temp` isn't equal to either "yes" or "no". – Jon Skeet Oct 05 '18 at 00:37
  • Good coding practice is to use *.equals* on constants("yes","no") . – NullPointer Oct 05 '18 at 00:39
  • 1
    If we assume that this is a binary choice, then an `else` would seem to be appropriate. – Elliott Frisch Oct 05 '18 at 00:48

1 Answers1

1

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;
swmcdonnell
  • 1,381
  • 9
  • 22