2
votes

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

}
4

4 Answers

2
votes

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.

2
votes

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");
2
votes

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.

1
votes

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
}