Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

JavaWorld Daily Brew

if..else exercise question



Hello, i have a question about the following code. I'll appreciate it if someone can help me out.

When i first tried to execute this code it gave me the error:

"The local variable animal may not have been initialized".

I thought I've initialized the variable for each if block so I re-checked the code and realized that:

if(hoursHome > 2) (shown below) was an extra and unnecessary sentence,

So i removed it but i didn't know it would also take care of the error for me. I'm using eclipse and i was wondering how removing this sentence is related to this error.

import javax.swing.JOptionPane;

public class PetAdvice {

public static void main(String[] args) {

int hoursHome,homeChoice;
String animal;

homeChoice = Integer.parseInt(JOptionPane.showInputDialog(null, "Please choose where you live"
+ "\n'1' for House, '2' for Apartment, '3' for Dormitory"));

hoursHome = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter number of hours spent at home"
+ "\n Enter '1' for (18 hours or more)"
+ "\n Enter '2' for (10 - 17 hours)"
+ "\n Enter '3' for (8 - 9 hours)"
+ "\n Enter '4' for (6 - 7 hours)"
+ "\n Enter '5' for (0 - 5 hours)"));

if(homeChoice == 1){
if(hoursHome == 1)
animal = "Pot-bellied pig";
else
if(hoursHome == 2)
animal = "Dog";
else
animal = "Snake";
}
else
if(homeChoice == 2){
if(hoursHome <= 2)
animal = "Cat";
else
if(hoursHome > 2) ----------> *********When i remove this sentence code works fine*********
animal = "Hamster";
}

else
if(hoursHome <= 4)
animal = "Fish";
else
animal = "Ant farm";

JOptionPane.showMessageDialog(null, "Pet Recommendation: " + animal); ******Where I get the error******
System.exit(0);

}

}