2012-08-23 247 views
3

此代码检查用户是否输入它是有效的。如果它不是数字,它将继续循环,直到收到一个数字。之后它将检查该数字是否在界限内或小于界限。它将继续循环,直到它收到一个入站号码。但我的问题是,当我打印选择时,它只显示最后插入数字后的前一个数字。为什么这样?使用扫描仪扫描Java输入

public void askForDifficulty(){ 
    System.out.println("Difficulty For This Question:\n1)Easy\n2)Medium\n3)Hard\nChoice: "); 
    int choice = 0; 
    boolean notValid = true; 
    boolean notInbound = true; 
    do{ 
     while(!input.hasNextInt()){ 
      System.out.println("Numbers Only!"); 
      System.out.print("Try again: "); 
      input.nextLine(); 
     } 
      notValid = false; 
      choice = input.nextInt(); 
    }while(notValid); 

    do{ 
     while(input.nextInt() > diff.length){ 
      System.out.println("Out of bounds"); 
      input.nextLine(); 
     } 
     choice = input.nextInt(); 
     notInbound = false; 
    }while(notInbound); 

    System.out.println(choice); 
} 

回答

3

这是因为input.nextInt()while条件内所消耗的整数,所以它后一个读取以下之一。 编辑您还需要两个环相结合,这样的:

int choice = 0; 
for (;;) { 
    while(!input.hasNextInt()) { 
     System.out.println("Numbers Only!"); 
     System.out.print("Try again: "); 
     input.nextLine(); 
    } 
    choice = input.nextInt(); 
    if (choice <= diff.length) break; 
    System.out.println("Out of bounds"); 
} 
System.out.println(choice); 
+0

我想你的代码。第二个输入只有在我输入数字时才被读取2次 – KyelJmD

+0

@KyelJmD哦,我看到了 - 你在那里还有另一个'nextInt',请参阅修正。 – dasblinkenlight

+0

顺便说一句你也可以检查这个问题吗? http://stackoverflow.com/questions/12082557/java-scanner-validation-returning-the-second-input – KyelJmD