Reputation: 19
This is what I have so far:
int question = sc.nextInt();
while (question!=1){
System.out.println("Enter The Correct Number ! ");
int question = sc.nextInt(); // This is wrong.I mean when user enters wrong number the program should ask user one more time again and again until user enters correct number.
// Its error is : duplicate local variable
}
Upvotes: 2
Views: 31549
Reputation: 1504162
You are trying to redeclare the variable inside the loop. You only want to give the existing variable a different value:
while (question != 1) {
System.out.println("Enter The Correct Number ! ");
question = sc.nextInt();
}
This is just an assignment rather than a declaration.
Upvotes: 2
Reputation: 1806
from my understanding your requirement is to prompt the user again and again until you match the correct number. If this is the case it would as follows: the loop iterates as long as the user enters 1
.
Scanner sc = new Scanner(System.in);
System.out.println("Enter The Correct Number!");
int question = sc.nextInt();
while (question != 1) {
System.out.println("please try again!");
question = sc.nextInt();
}
System.out.println("Success");
Upvotes: 2
Reputation: 28439
you are declaring int question outside the loop and then again inside the loop.
remove the int declaration inside the loop.
In Java the scope of a variable is dependent on which clause it is declare in. If you declare a variable INSIDE a try or a while or many other clauses, that variable is then local to that clause.
Upvotes: 2
Reputation: 25613
Reuse the question
variable instead of redeclaring it.
int question = sc.nextInt();
while (question != 1) {
System.out.println("Enter The Correct Number ! ");
question = sc.nextInt(); // ask again
}
Upvotes: 1