2

I have a little problem with my console app. Applications should get numbers from user and add them to the list but if input is "c", it should turn off. I cant figured out how to verify the "c" variable without hanging the app with Scanner.nextLine() and exit the loop.

public void getNumbersFromUser() {

  Scanner scanner = new Scanner(System.in);
  int number;
  boolean flag = true;

  do{
     System.out.println("Enter a number");

     while(!scanner.hasNextInt()) {
        System.out.println("Thats not a number !");
        scanner.next();
     }
        number = scanner.nextInt();
        list.add(number);
        System.out.println(list);

  }
  while(flag);
Cœur
  • 37,241
  • 25
  • 195
  • 267
M.Matt
  • 69
  • 5
  • 3
    You already use `scanner.next()`, so why not check that isn't a "c"? And if you don't like the "Thats not a number !" print for "c" input, then you can't check for number first. Read as String and then convert to int when appropriate. – Tom Mar 05 '19 at 15:20

2 Answers2

2

One way to do it is to use Scanner.next(), which will block waiting for input, and check the input with Integer.parseInt() yourself:

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

do {
    System.out.println("Enter a number");
    String next = scanner.next();
    if (next.equals("c")) {
        break;
    }

    try {
        int number = Integer.parseInt(next);
        list.add(number);
        System.out.println(list);
    } catch (NumberFormatException ex) {
        System.out.println("That's not a number !");
    }
} while (true);
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
1

It's better you to get the input with next(), and to not add third part libraries, create a helper method to check if input is a number:

Helper method:

public static boolean isNumeric(String strNum) {
    try {
        int d = Integer.parseInt(strNum);
    } catch (NumberFormatException | NullPointerException nfe) {
        return false;
    }
    return true;
}

Using it in a do/while loop:

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

do {
    System.out.println("Enter a number");
    String input = scanner.next();

    if(!isNumeric(input)) {
        if(!input.equals("c")) {
            System.out.println("Thats not a number !");
            continue; // will restart the loop
        }
        else break; // will exit if input is "c"
    }
    else {
        list.add(Integer.parseInt(input));
        System.out.println(list);
    }
}
while(flag);

Live example here.

tomrlh
  • 1,006
  • 1
  • 18
  • 39