HasNextInt() Infinite loop [closed]

对着背影说爱祢 提交于 2019-12-13 11:28:38

问题


//input: multiple integers with spaces inbetween
    Scanner sc = new Scanner(System.in);
    while(sc.hasNextInt())
    {
      //add number to list
    }

sc.hasNextInt() is waiting for an integer. It only breaks out if you input a non-integer character.

I saw a solution here before not too long ago but i cant find it anymore.

The solution (was the best if you ask me) was using two scanners. I cant seem to figure out how it used two scanners to go around this problem.

sc.NextLine() maybe?


A user can input multiple integers the amount is unknown. Ex: 3 4 5 1. There is a space inbetween them. All i want to do is read the integers and put it in a list while using two scanners.


回答1:


Based on your comment

A user can input multiple integers the amount is unknown. Ex: 3 4 5 1. There is a space inbetween them. All i want to do is read the integers and put it in a list while using two scanners.

You are probably looking for:

  • scanner which will read line from user (and can wait for next line if needed)
  • another scanner which will handle splitting each number from line.

So your code can look something like:

List<Integer> list = new ArrayList<>();
Scanner sc = new Scanner(System.in);
System.out.print("give me some numbers: ");
String numbersInLine = sc.nextLine();//I assume that line is in form: 1 23 45 

Scanner scLine = new Scanner(numbersInLine);//separate scanner for handling line
while(scLine.hasNextInt()){
    list.add(scLine.nextInt());
}
System.out.println(list);



回答2:


Try this:

while (sc.hasNext()) {
    if (sc.hasNextInt()) {
       // System.out.println("(int) " + sc.nextInt());
       // or add it to a list
    }
     else {
       // System.out.println(sc.next());
       // or do something
    }
}



回答3:


    Scanner sc = new Scanner(System.in);
    while(sc.hasNextInt())
    {

        System.out.println("Hi");
        System.out.println("Do you want to exit ?");
        Scanner sc2 = new Scanner(System.in);
        if(sc2.next().equalsIgnoreCase("Yes")){
            break;
        }
     }


来源:https://stackoverflow.com/questions/33084212/hasnextint-infinite-loop

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