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()

;

1

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.