[英]Can't read slash ( / ) with Scanner Java
I want to check if an user types a mathematical character with scanner.hasNext("[-+/*]") and it seems to not detect the "/" 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();
}
}
Slash character is identified using \\\\/
pattern斜线字符使用
\\\\/
模式标识
Update your pattern to [-+\\\\/*]
将您的模式更新为
[-+\\\\/*]
You can use the Pattern class as per below:您可以按照以下方式使用Pattern类:
Pattern.matches("([/+-.*])", typed)
Here is an example:下面是一个例子:
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();
output:输出:
3
2
1
/
typed[/+-*]: /
*
typed[/+-*]: *
-
typed[/+-*]: -
+
typed[/+-*]: +
you can use \\\\ / instead of /您可以使用 \\\\ / 代替 /
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();
}
}
The problem was solved by not using any kind of regex but instead checking if the input is contained in the operations string like this:问题是通过不使用任何类型的正则表达式解决的,而是检查输入是否包含在操作字符串中,如下所示:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.