[英]how to use .contains to select certain letters of the alphabet
我需要用戶輸入:
- 沒有數字
- 長度為 4 個字符
- 只使用字母表中的某些字母 [R, B, G, P, Y, O]
我已經想出了如何不使用數字並且只有 4 個字符的長度,但是,我似乎無法弄清楚如何限制字母表中的某些字母(除 R、B、G、P、Y、O 之外的所有字母。)
guess = input.nextLine();
guess = guess.toUpperCase();
while (guess.length() != 4 || guess.contains("[0-9]") || guess.contains("[ACDEFHIJKLMNQSTUVWXZ]")) {
System.out.println("Bad input! Try again");
System.out.println("Use the form \"BGRY\"");
guess = input.nextLine();
}
這是我到目前為止的代碼,它似乎不起作用
這樣做:
while(!guess.matches("[RBGPYO]{4}")) {
// ...
}
演示:
public class Main {
public static void main(String s[]) {
// Tests
System.out.println(matches("RBGPYO"));
System.out.println(matches("RBGP"));
System.out.println(matches("R1BGP"));
System.out.println(matches("ABCD"));
System.out.println(matches("1234"));
System.out.println(matches("BGPY"));
System.out.println(matches("BYPG"));
}
static boolean matches(String input) {
return input.matches("[RBGPYO]{4}");
}
}
輸出:
false
true
false
false
false
true
true
還有很多不使用Regex的方法。
在這種情況下,您不能使用String::contains
,因為此方法適用於特定的字符序列,並且您的用例過於具體。 但是,您可以利用List::contains
的優勢,只要使用java-stream將String
理解為List<Character>
就可能更有用:
List<Integer> characters = "RBGPYO".chars()
.boxed()
.collect(Collectors.toList());
boolean matches = guess.length() == 4 &&
guess.toUpperCase().chars().allMatch(characters::contains);
如果您不喜歡此功能,請使用一個很好的舊方法 for 循環:
List<Character> characters = Arrays.asList('R', 'B', 'G', 'P', 'Y', 'O');
boolean matches = guess.length() == 4;
if (matches) {
for (char ch : guess.toUpperCase().toCharArray()) {
if (!characters.contains(ch)) {
matches = false;
break; // it's important to break the cycle
}
}
}
無論如何,重要的是在檢查字符之前檢查長度。 只要guess
應包含字符並具有特定長度,這就是有效的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.