我需要检查扫描仪是否持有此信息:"添加(此处为任何整数)"
这是代码:
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);
}
}
我评论了我需要的地方,请在代码中查找。任何帮助,将不胜感激。提前致谢!
答案 0 :(得分:1)
您可以使用正则表达式,例如"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);
}