退出 do-while 循环应用程序

我的控制台应用程序有一点问题。应用程序应该从用户那里获取数字并将它们添加到列表中,但如果输入是“c”,它应该关闭。我不知道如何在不挂起应用程序Scanner.nextLine()并退出循环的情况下验证“c”变量。


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


慕尼黑8549860
浏览 214回答 2
2回答

月关宝盒

最好使用 获取输入next(),而不是添加第三方库,创建一个辅助方法来检查输入是否为数字:辅助方法:public static boolean isNumeric(String strNum) {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; int d = Integer.parseInt(strNum);&nbsp; &nbsp; } catch (NumberFormatException | NullPointerException nfe) {&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }&nbsp; &nbsp; return true;}在 do/while 循环中使用它:Scanner scanner = new Scanner(System.in);List<Integer> list = new ArrayList<>();boolean flag = true;do {&nbsp; &nbsp; System.out.println("Enter a number");&nbsp; &nbsp; String input = scanner.next();&nbsp; &nbsp; if(!isNumeric(input)) {&nbsp; &nbsp; &nbsp; &nbsp; if(!input.equals("c")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Thats not a number !");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue; // will restart the loop&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else break; // will exit if input is "c"&nbsp; &nbsp; }&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; list.add(Integer.parseInt(input));&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(list);&nbsp; &nbsp; }}while(flag);现场示例在这里。

临摹微笑

一种方法是使用Scanner.next(),它将阻止等待输入,并Integer.parseInt()自己检查输入:List<Integer> list = new ArrayList<>();Scanner scanner = new Scanner(System.in);do {&nbsp; &nbsp; System.out.println("Enter a number");&nbsp; &nbsp; String next = scanner.next();&nbsp; &nbsp; if (next.equals("c")) {&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; int number = Integer.parseInt(next);&nbsp; &nbsp; &nbsp; &nbsp; list.add(number);&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(list);&nbsp; &nbsp; } catch (NumberFormatException ex) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("That's not a number !");&nbsp; &nbsp; }} while (true);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java