在nextInt()之后跳过扫描仪nextLine()

时间:2019-10-27 11:34:07

标签: java string input java.util.scanner

我正在尝试制作一个循环的计算器程序,用户可以在其中输入数字,然后他希望对该数字执行的操作,直到他输入“ =”作为运算符为止。包含结果的变量在类中初始化为零,并且应用的默认运算符为“ +”。

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 :
4
Operator :
Please enter a valid operator.
Number :
67
Operator :
Please enter a valid operator.
Number :

程序不允许我在运算符中输入内容,而直接跳到下一个int输入内容。我一直在尝试各种方式来编写此代码,例如将该部分从循环中取出,但它仍然是相同的错误,我看不到是什么原因造成的。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

这是因为nextInt函数不会读取换行符。您需要先消耗掉该字符,然后才能再次接受用户输入

只需在scan.nextLine();函数调用之后添加nextInt语句。

System.out.println("Number :");
int userEntry = scan.nextInt();

scan.nextLine();   // this will consume the new line character

System.out.println("Operator :");
String operation = scan.nextLine();

有关更多信息,请参见scanner is skipping user input

答案 1 :(得分:0)

/** 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();
    }
}