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
Advertisement
Answer
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."); } }