Search code examples
javaloopsinfinite

HasNextInt() Infinite loop


//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.


Solution

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