Exit do-while loop application

M.Matt :

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);
Karol Dowbecki :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=147381&siteId=1