我有问题。我希望我的程序问我插入一个单词,这个单词的字母必须包含在一个数组中。
目前,我想如果字母包含在数组中,打印(“字母是正确的”),否则打印(“字母不正确”)。
但总是回来(“这封信不正确”),为什么?
请帮助我!
public class Utils {
Scanner ent = new Scanner(System.in);
String insertedLetter = "";
String letters[] = {"a", "b", "c", "d", "e", "f", "g", "i", "j", "l", "m", "n", "o", "p", "r"};
String saveLetter = "";
public void askLetter() {
for (int i = 0; i < letters.length; i++) {
saveLetter += " " + letters[i] + ",";
}
System.out.println("Insert a word that contains these letters " + saveLetter);
insertedLetter = ent.nextLine();
if (saveLetter.equals(insertedLetter)) {
System.out.println("The letter is correct");
} else {
System.out.println("The letter is incorrect");
}
}
}
答案 0 :(得分:1)
这样做的简单方法如下:
boolean contained = true;
for (int i = 0; i < insertedLetter.length(); i++) {
if (saveLetter.indexOf(insertedLetter.charAt(i)) == -1) {
contained = false;
break;
}
}
if (contained) {
System.out.println("The letters are all contained in the saveLetter array");
} else {
System.out.println("One or more of the input letters are not contained in the saveLetter array");
}