[英]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.