how can i use java scanner in while loop

前端 未结 4 765
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-21 15:35

This is what I have so far:

int question = sc.nextInt(); 

while (question!=1){

    System.out.println(\"Enter The Correct Number ! \");

    int question =         


        
相关标签:
4条回答
  • 2020-12-21 15:59

    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
    }
    
    0 讨论(0)
  • 2020-12-21 16:01

    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.

    0 讨论(0)
  • 2020-12-21 16:02

    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");
    
    0 讨论(0)
  • 2020-12-21 16:12

    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.

    0 讨论(0)
提交回复
热议问题