0

I'm trying to add scanner inputs into an ArrayList, but I can't exit out the loop after I have entered the inputs. How can I exit this loop after I'm done entering inputs?

ArrayList<String> inputs = new ArrayList<>();
int i = 0;
while(scan.hasNext()){//while there is an hasNext
    inputs.add(scan.next());// add to the inputs array of queue
    i++;
}scan.close()

;

Mark Rotteveel
  • 82,132
  • 136
  • 114
  • 158
James
  • 67
  • 4
  • [Java: Infinite loop using Scanner in.hasNextInt()](https://stackoverflow.com/questions/1794281/java-infinite-loop-using-scanner-in-hasnextint/2762976#2762976) – paulina moreno Nov 25 '20 at 05:02

1 Answers1

3

You can check if the user entered a string with a length of 0, i.e., "", indicating they are done:

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Queue<String> queue = new LinkedList<>();
        System.out.println("Enter input:");
        String input = "";
        try (Scanner scan = new Scanner(System.in)) {
            while (scan.hasNextLine()
                    && (input = scan.nextLine()).length() != 0) {
                queue.add(input);
            }
        }
        System.out.printf("Queue: %s%n", queue);
    }
}

Example Usage:

Enter input:
A
B
C

Queue: [A, B, C]
Sash Sinha
  • 11,515
  • 3
  • 18
  • 35