VozMajal
VozMajal

Reputation: 23

Adding unknown number of numbers to arraylist

I'm trying to make an Insertion Sort algorithm in Java, and I want it to read user input, and he/she can put however many numbers they wish (We'll say they're all integers for now, but long run it would be nice to be able to do both integers and doubles/floats), and I want the algorithm to sort them all out. My issue is that when I run this code to see if the integers are adding correctly, my loop never stops.

public class InsertionSort {
public static void main(String[] args){
    System.out.println("Enter the numbers to be sorted now: ");
    ArrayList<Integer> unsortNums = new ArrayList<Integer>();
    Scanner usrIn = new Scanner(System.in);

    while(usrIn.hasNextInt()) {
        unsortNums.add(usrIn.nextInt());
        System.out.println(unsortNums);    //TODO: Doesn't stop here
    }
    sortNums(unsortNums);
  }
}

Now, I suspect it has something to do with how the scanner is doing the .hasNextInt(), but I cannot for the life of me figure out why it isn't stopping. Could this be an IDE specific thing? I'm using Intellij Idea.

Let me know if I left anything out that I need to include.

Upvotes: 2

Views: 1338

Answers (2)

Makoto
Makoto

Reputation: 106460

Your code will stop as long as you stop adding numbers to your input stream. nextInt() is looking for another integer value, and if it can't find one, it'll stop looping.

Give it a try - enter in any sequence of characters that can't be interpreted as an int, and your loop will stop.

As a for-instance, this sequence will cease iteration: 1 2 3 4 5 6 7 8 9 7/. The reason is that 7/ can't be read as an int, so the condition for hasNextInt fails.

Upvotes: 1

Mureinik
Mureinik

Reputation: 311808

When using a scanner on System.in, it just blocks and waits for the user's next input. A common way of handling this is to tell the user that some magic number, e.g., -999, will stop the input loop:

System.out.println("Enter the numbers to be sorted now (-999 to stop): ");
List<Integer> unsortNums = new ArrayList<Integer>();
Scanner usrIn = new Scanner(System.in);

int i = usrIn.nextInt();
while(i != -999) {
    unsortNums.add(i);
    i = usrIn.nextInt();
}

Upvotes: 0

Related Questions