how to stop while loop when taking input without words: "exit" etc

I have to take inputs until EOF (white space or end of line). For example:

1
2
3
4
// end of taking input

I'm using Scanner to take inputs. I tried this solution.

    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);
        ArrayList<String> password = new ArrayList<>();
        String input;

        while (!(input = sc.nextLine()).equals("")) {
            password.add(input);
        }

        boolean[] lengthValidation = lengthCheck(password);
        boolean[] passwordContainCheck = containCheck(password);

        print(lengthValidation, passwordContainCheck);
    }

I can't use this, due to uri does not take it variant of answer

while(true) {
   String input = sc.nextLine();
   
   if (input.equals(""))
       break;
}

Upvotes: 0

Views: 52

Answers (2)

WJS
WJS

Reputation: 40044

I have to take inputs until EOF (white space or end of line).

Try the following. One entry per line. Terminate with an empty line. You can store them in a list and use them when the loop terminates.

Scanner input = new Scanner(System.in);
String v;
List<String> items = new ArrayList<>();
while (!(v = input.nextLine()).isBlank()) {
    items.add(v);
}
System.out.println(items);
    

Upvotes: 1

Matte97
Matte97

Reputation: 21

Maybe this is what you are looking for, Scanner take input until it meets an empty line, then the loop stop

Scanner sc = new Scanner(System.in);
    ArrayList<String> password = new ArrayList<>();
    String input;

    while (true) {
        input = sc.nextLine();
        if (input.equals("")) break;
        password.add(input);
    }

Upvotes: 0

Related Questions