1

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
  • 100,966
  • 191
  • 140
  • 197
James
  • 65
  • 5
  • [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

4

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) {
        Scanner scan = new Scanner(System.in);
        Queue<String> queue = new LinkedList<>();
        System.out.println("Enter input:");
        String input;
        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
  • 18,743
  • 3
  • 23
  • 40