[英]How to check if a Scanner is a specific String + any positive integer [Java]
我需要检查扫描仪是否持有这个:“添加(这里的任何整数)”这是代码:
import java.util.Scanner;
public class BottleGame {
void startGame() {
System.out.println("Welcome to the bottle game! Please type \"help\" to learn about the game.");
System.out.println("If you already know how the game works, feel free to start!");
Scanner scanner = new Scanner(System.in);
commands(scanner);
}
void commands(Scanner myScanner) {
boolean again = false;
do {
String response = myScanner.next();
if (response.equals("help")) {
System.out.println("+------------------------+");
System.out.println("help - brings up this menu");
System.out.println("add X - makes X bottles");
System.out.println("remove X - deletes X bottles");
System.out.println("flip - flips a bottle");
System.out.println("+------------------------+");
again = true;
}
//Need to check if response equals "add" + any integer here
}
while(again == true);
}
}
我评论了我需要这个的地方,请在代码中寻找它。 任何帮助,将不胜感激。 提前致谢!
您可以为此使用正则表达式,例如"add\\\\s+\\\\d+"
,它将匹配单词 add 后跟一个或多个空格,然后是一个或多个带有String.matches(String)
数字
} else if (response.matches("add\\s+\\d+")) {
System.out.println("Add");
}
然后解析该值,您可以将数字分组并调用String.replaceAll(String, String)
然后使用Integer.parseInt(String)
像
} else if (response.matches("add\\s+\\d+")) {
int v = Integer.parseInt(response.replaceAll("add\\s+(\\d+)", "$1"));
System.out.println(v);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.