使用Scanner Java无法读取斜杠(/)

时间:2019-12-06 05:29:15

标签: java math operation

我想检查用户是否使用scanner.hasNext(“ [-+ / *]”)键入数学字符,并且似乎无法检测到“ /”操作。

public void checkSign(Scanner scanner) {
        for (;!scanner.hasNext("[-+/*]");) {
                  System.err.println("You have not typed an operation (ex: + , - , * , /)!");
                  System.out.println("Try again!");
                  scanner.next();
             } 
    }

4 个答案:

答案 0 :(得分:3)

使用\\/模式识别斜杠字符

将您的模式更新为[-+\\/*]

答案 1 :(得分:0)

您可以按照以下方式使用Pattern类:

Pattern.matches("([/+-.*])", typed)

这里是一个例子:

Scanner scanner = new Scanner(System.in);
String typed = null;
while (scanner.hasNext()) {
    typed = scanner.next();
    if (Pattern.matches("([/+-.*])", typed)) {
        System.out.println("typed[/+-*]: " + typed);
    } 
}
scanner.close();   

输出:

3
2
1
/
typed[/+-*]: /
*
typed[/+-*]: *
-
typed[/+-*]: -
+
typed[/+-*]: +

答案 2 :(得分:0)

您可以使用\\ /代​​替/

public void checkSign(Scanner scanner) {
        for (;!scanner.hasNext("[-+\\/*]");) {
                  System.err.println("You have not typed an operation (ex: + , - , * , /)!");
                  System.out.println("Try again!");
                  scanner.next();
             } 
    }

答案 3 :(得分:0)

通过不使用任何正则表达式解决了问题,而是检查输入是否包含在操作字符串中,如下所示:

public String checkSign(Scanner scanner) {  
    String line;
    scanner.nextLine();
    for (;!"+-*/".contains(line = scanner.nextLine());) {
               System.err.println("You have not typed an operand! (ex: + , - , * , /)!");
               System.out.println("Try again!");
               scanner.next();
    } 
    return line;
}