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

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

Loop 和 Try/Catch 內的 Scanner.nextLine 跳過詢問輸入

Loop 和 Try/Catch 內的 Scanner.nextLine 跳過詢問輸入

大話西游666 2023-07-19 10:48:45
在嘗試這些讀取 int 輸入的建議后,掃描儀在使用 next() 或 nextFoo() 之后跳過 nextLine() 嗎?無法弄清楚輸入為什么不消耗換行符。這是運行jdk 11的linux。import java.util.Scanner;public class NumbFile {? ? public static void main(String[] args) throws Exception {? ? ? ? int i = 100;? ? ? ? int powerNumber;? ? ? ? boolean status = true;? ? ? ? ? ? do {? ? ? ? ? ? ? ? try {? ? ? ? ? ? ? ? ? ? System.out.print("Type a number: ");? ? ? ? ? ? ? ? ? ? Scanner sc = new Scanner(System.in);? ? ? ? ? ? ? ? ? ? powerNumber = Integer.parseInt(sc.nextLine());? ? ? ? ? ? ? ? ? ? System.out.println(i * powerNumber);? ? ? ? ? ? ? ? ? ? sc.close();? ? ? ? ? ? ? ? } catch (NumberFormatException exc) {? ? ? ? ? ? ? ? ? ? exc.printStackTrace();? ? ? ? ? ? ? ? ? ? status = false;? ? ? ? ? ? ? ? }? ? ? ? ? ? } while(status);? ? }}這應該僅在沒有 int 輸入的情況下停止循環。
查看完整描述

1 回答

?
暮色呼如

TA貢獻1853條經驗 獲得超9個贊

刪除sc.close();. 這會關閉你的Scanner(應該在循環之前聲明一次),但它也會關閉System.in(你不能重新打開它)。


int i = 100;

boolean status = true;

Scanner sc = new Scanner(System.in);


do {

    try {

        System.out.print("Type a number: ");

        int powerNumber = Integer.parseInt(sc.nextLine());

        System.out.println(i * powerNumber);

    } catch (NumberFormatException exc) {

        exc.printStackTrace();

        status = false;

    }

} while (status);


查看完整回答
反對 回復 2023-07-19
  • 1 回答
  • 0 關注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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