I'm writing a simple simulation as part of my study (yes, I'm just beginner in Java). In it I'm taking input from user via Scanner and I want to check that input for valid format (only numbers) and valid range. I faced difficulties - input value does not come out of "while" loop. Could you please give me a tip? I'll appreciate it!
Here is part of my code you might be interested in:
// check for invalid input
String input;
boolean valid = false;
while (!valid){
try{
input = sc.next();
user = Integer.parseInt(input);
valid = true;
}catch (NumberFormatException ex) {
System.out.println(ex);
System.out.println("Number but not a character or a symbol!");
}
System.out.println("Try once more!");
}
// interaction with user;
while (user !=3){
if (user ==1){
System.out.println("What angle I should set?");
userChange = sc.nextDouble();
shot.userAngle(userChange);
shot.show();
}
else if (user ==2){
System.out.println("What speed I should set?");
userChange = sc.nextDouble();
shot.userSpeed(userChange);
shot.show();
}
else {
System.out.println("Wrong number!");
}
System.out.println("What you want to change?");
user = sc.nextInt();
}
It says that variable "user" might not be set.