Scanner nextInt() and hasNextInt() problems

北战南征 提交于 2020-01-15 08:54:05

问题


I'm investigating why scan.nextInt() consumes the previous integer from the second iteration onwards. Can anyone make sense of what's going on and also explain what "The scanner does not advance past any input" means exactly?

Please ignore the infinite loop. It's only for testing purposes.

Example:
Enter new data: 0
0
data entered
Enter data again: 1
executed
Enter new data: 1 <- this value is automatically entered (taken from previous input)
data entered
Enter data again:

    while(true)
    {
        System.out.print("Enter new data: ");
        System.out.println(scan.nextInt());
        //scan.nextLine();    //must include but I'm not sure why 
        System.out.println("data entered");
        System.out.print("Enter data again: ");
        if(scan.hasNextInt())
        {
            System.out.println("executed");
            //scan.nextLine();    //must include this too but not sure why
        }
    }

回答1:


The general pattern is this :

while(scan.hasNextInt())
{
    System.out.println(scan.nextInt());
}

First you make sure that there is next int and if there is next one you do something with it. You are doing it other way round. First you consume it, than you check whether there is another one, which is wrong.

Why should we call hasNextXXX before nextXXX ? Because nextXXX can throw NoSuchElementException if there isn't such next token. Look at this example :

String str = "hello world";
Scanner scan = new Scanner(str);

There is no integer in this string, which means that

System.out.println(scan.nextInt());

will throw NoSuchElementException. But if you use the while loop that I wrote you first check that there is an Integer in the input before you try doing anything with it. Therefore this is the standard pattern instead of handling unnecessary exceptions.



来源:https://stackoverflow.com/questions/20791211/scanner-nextint-and-hasnextint-problems

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!