字符(操作员)的扫描仪输入如何工作?

How the scannner input for character ( Operators ) work?

我写了一个关于用户输入的结果的代码,请解释一下这个字符输入是如何工作的,因为当我使用

char operation = s.nextLine().charAt(0);

而不是

char operation = s.next().charAt(0);

Eclipse 显示错误。

代码-

    System.out.println("Enter First Number:");
    int a = s.nextInt();

    System.out.println("Enter Second Number:");
    int b = s.nextInt();

    System.out.println("Which Operation you want to execute?");
    s.hasNextLine();
    char operation = s.next().charAt(0);    

    int result = 0;

    switch (operation) {
    case '+' :
        result = a + b;
        break;
    case '-' :
        result = a - b;
        break;
    case '*' :
        result = a * b; 
        break;
    case '/' :
        result = a / b;
        break;
    case '%' :
        result = a % b;
        break;
    default:
        System.out.println("Invalid Operator!");
    }
    System.out.println(result);
    s.close();
}

}

来自扫描仪的文档https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.

因此,如果您输入 .nextLine(),您实际上是在读取自上次输入到下一行后剩下的内容(即什么也没有)。这可以用这段代码来证明

Scanner s = new Scanner(System.in);
System.out.println("Enter First Number:");
int a = s.nextInt();

System.out.println("Enter Second Number:");
int b = s.nextInt();

System.out.println("Which Operation you want to execute?");
s.hasNextLine();
String s1 = s.nextLine();
String s2 = s.nextLine();
System.out.println(s1);
System.out.println(s2);
//char operation = s1.charAt(0); -> error
char operation = s2.charAt(0);//operator is read

第一次打印(s1)不会打印任何东西。第二个将打印运算符。

问题不是因为s.nextLine();相反,这是因为 s.nextInt()。检查 Scanner is skipping nextLine() after using next() or nextFoo()? 以了解更多信息。

使用

int a = Integer.parseInt(s.nextLine());

而不是

int a = s.nextInt();

我建议您创建一个效用函数,例如getInteger 中创建,以处理异常情况。