duronic
duronic

Reputation: 167

How to stop reading from a scanner if the user inputs a specific keyword?

I need to be able to enter a random number of integers into the console and then enter a special character such as Q when I am finished. However, I am not sure how to validate if the input is an int or not.

The point is for the user to enter x amount of ints, which get sent from client to server and the server returns the result from a simple equation. I plan on sending them one at a time as it can be any amount of ints entered.

I have tried several different ways. I have tried using hasNextInt. I tried nextLine then added each input to an ArrayList then parsed the input.

List<String> list = new ArrayList<>();
String line;

while (!(line = scanner.nextLine()).equals("Q")) {
    list.add(line);
}

list.forEach(s -> os.write(parseInt(s)));

This is another loop I had originally which validates the input fine, but i'm not sure how to exit the loop when done.

while (x < 4) {
    System.out.print("Enter a value: ");

    while (!scanner.hasNextInt()) {    
        System.out.print("Invalid input: Integer Required (Try again):");
    }

    os.write(scanner.nextInt());
    x++;
}

Any help would be appreciated. Thanks

Upvotes: 1

Views: 1443

Answers (2)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79085

Do it as follows:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        List<Integer> list = new ArrayList<Integer>();
        String input = "";
        while (true) {
            System.out.print("Enter an integer (Q to quit): ");
            input = in.nextLine();
            if (input.equalsIgnoreCase("Q")) {
                break;
            }
            if (!input.matches("\\d+")) {
                System.out.println("This is an invalid entry. Please try again");
            } else {
                list.add(Integer.parseInt(input));
            }
        }
        System.out.println(list);
    }
}

A sample run:

Enter an integer (Q to quit): a
This is an invalid entry. Please try again
Enter an integer (Q to quit): 10
Enter an integer (Q to quit): b
This is an invalid entry. Please try again
Enter an integer (Q to quit): 20
Enter an integer (Q to quit): 10.5
This is an invalid entry. Please try again
Enter an integer (Q to quit): 30
Enter an integer (Q to quit): q
[10, 20, 30]

Notes:

  1. while(true) creates an infinite loop.
  2. \\d+ allows only digits i.e. only an integer number.
  3. break causes the loop to break.

Upvotes: 2

cegredev
cegredev

Reputation: 1579

Here you go:

Scanner scanner = new Scanner(System.in);
List<Integer> list = new ArrayList<Integer>();

while (scanner.hasNext()) {
    String line = scanner.nextLine();

    if (line.equals("Q")) {
        scanner.close();
        break;
    }

    try {
        int val = Integer.parseInt(line);
        list.add(val);
    } catch (NumberFormatException e) {
        System.err.println("Please enter a number or Q to exit.");
    }
}

Upvotes: 2

Related Questions