Reputation: 781
I am very new to Java and I'm trying to get a small code to work, but I get the message "The local variable tal2 may not be defined". I see the issue, but I'm not really sure how to solve it.
The program is supposed to print the line "Thank you" if the first input is 0, else let the user proceed to input #2 and then run the second else if statement.
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
int tal1;
int tal2;
tal1 = stdIn.nextInt();
if (tal1 == 0 ) {
System.out.println("Thank you.");
} else {
tal2 = stdIn.nextInt();
}
if (tal1 > tal2) {
System.out.println(tal1 + " is greater than " + tal2);
} else {
System.out.println(tal2 + " is greater than " + tal1);
}
}
Upvotes: 0
Views: 99
Reputation: 168
because second input statement is inside first else block. So if you will enter 0 as first input so then first else bock will not be executed and it will not ask for input second time and will go to the else bock of second if. so put second input statement out of first if-else block.
Upvotes: 0
Reputation: 201507
You didn't call System.exit()
like you probably meant to.
if (tal1 == 0) {
System.out.println("Thank you.");
System.exit(0);
}
You might also just return;
Alternatively, you might move your other statements into your first else
block
} else {
tal2 = stdIn.nextInt();
if (tal1 > tal2) {
System.out.println(tal1 + " is greater than " + tal2);
} else {
System.out.println(tal2 + " is greater than " + tal1);
}
}
Upvotes: 4
Reputation: 575
Initialize your variables, as these are local variables ant it should always be intialized.
int tal1 = 0;
int tal2 = 0;
You need to call System.exit(0)
, if you want to exit from the system.
Upvotes: 0