我正在尝试制作一个循环的计算器程序,用户可以在其中输入一个数字,然后输入他希望对该数字执行的操作,直到他输入“=”作为运算符。包含结果的变量在类中初始化为零,并且应用的默认运算符是“+”。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();
}
}
添加回答
举报
0/150
提交
取消