2

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 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

could you please tick as answer or upvote if you are satisfied :)
2

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.

Comments

1

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
}

1 Comment

Thank u All Fella :) I'm trying

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.