I want to check if an user types a mathematical character with scanner.hasNext("[-+/*]") and it seems to not detect the "/" operation.
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.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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.