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

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

掃描儀 nextLine() 在 nextInt() 之后被跳過

掃描儀 nextLine() 在 nextInt() 之后被跳過

拉丁的傳說 2024-01-05 10:31:51
我正在嘗試制作一個循環的計算器程序,用戶可以在其中輸入一個數字,然后輸入他希望對該數字執行的操作,直到他輸入“=”作為運算符。包含結果的變量在類中初始化為零,并且應用的默認運算符是“+”。import java.util.Scanner;public class main {    public static void main(String[] args) {        Scanner scan = new Scanner(System.in);        Calculator c = new Calculator();        boolean flow = true;        while(flow) {            System.out.println("Number :");            int userEntry = scan.nextInt();            System.out.println("Operator :");            String operation = scan.nextLine();            switch(operation) {            case "+":                c.setOperation(Calculator.ADDITION);                break;            case "-":                c.setOperation(Calculator.SOUSTRACTION);                break;            case "*":                c.setOperation(Calculator.MULTIPLICATION);                break;            case "=":                c.getResult();                return;            default:                System.out.println("Please enter a valid operator.");            }            c.apply(userEntry);            c.getResult();        }    }}但每次我嘗試運行該程序時,我都會得到這個結果Number :4Operator :Please enter a valid operator.Number :67Operator :Please enter a valid operator.Number :該程序不允許我將輸入放入運算符中并直接跳到下一個 int 輸入。我一直在嘗試各種方法來編寫此內容,例如將該部分從循環中取出,但它仍然是相同的錯誤,我看不出導致此問題的原因。任何幫助將非常感激。
查看完整描述

1 回答

?
慕無忌1623718

TA貢獻1744條經驗 獲得超4個贊

/** Scanning problems */

class Scanning {

    public static void main(String[] args) {

        int num;

        String txt;

        Scanner scanner = new Scanner(System.in);


        // Problem: nextLine() will read previous nextInt()

        num = scanner.nextInt();

        txt = scanner.nextLine();


        // solution #1: read full line and convert it to integer

        num = Integer.parseInt(scanner.nextLine());

        txt = scanner.nextLine();


        // solution #2: consume newline left-over

        num = scanner.nextInt();

        scanner.nextLine();

        txt = scanner.nextLine();

    }

}


查看完整回答
反對 回復 2024-01-05
  • 1 回答
  • 0 關注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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