亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

退出 do-while 循環應用程序

退出 do-while 循環應用程序

慕尼黑8549860 2022-07-20 16:30:43
我的控制臺應用程序有一點問題。應用程序應該從用戶那里獲取數字并將它們添加到列表中,但如果輸入是“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);
查看完整描述

2 回答

?
月關寶盒

TA貢獻1772條經驗 獲得超5個贊

最好使用 獲取輸入next(),而不是添加第三方庫,創建一個輔助方法來檢查輸入是否為數字:


輔助方法:


public static boolean isNumeric(String strNum) {

    try {

        int d = Integer.parseInt(strNum);

    } catch (NumberFormatException | NullPointerException nfe) {

        return false;

    }

    return true;

}

在 do/while 循環中使用它:


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

現場示例在這里。


查看完整回答
反對 回復 2022-07-20
?
臨摹微笑

TA貢獻1982條經驗 獲得超2個贊

一種方法是使用Scanner.next(),它將阻止等待輸入,并Integer.parseInt()自己檢查輸入:


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


查看完整回答
反對 回復 2022-07-20
  • 2 回答
  • 0 關注
  • 243 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號