繁体   English   中英

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

[英]Scanner nextLine() is being skipped after nextInt()

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

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 输入。 我一直在尝试各种方式来写这个,比如把那部分从循环中取出,但它仍然是同样的错误,我看不出是什么原因造成的。 任何帮助将非常感激。

那是因为nextInt function 不读取换行符。 您需要先使用该字符,然后才能再次接受用户输入

只需添加scan.nextLine(); nextInt function 调用后的语句。

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

有关这方面的更多信息,请参阅扫描仪正在跳过用户输入

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM