我在 Java 中有以下方法:
void searchPhrase(String[] phrase){
searchResult = new int[phrase.length];
int j=0, k=0;
for (int i=0; i<frase.length;i++)
if (!phrase[i].equals(alphabet[k])){
System.out.println("\nLetter "+phrase[i]+" was not found when comparing it to "+alphabet[k]);
k++;
}
else{
System.out.println("\nLetter "+phrase[i]+" was found when comparing it to "+alphabet[k]);
searchResult[j] = i;
k=0;
}
}
我有两个字符串数组,短语和字母表。短语是任何给定的短语,字母表包含从 A 到 Z 的字母表。
我需要接收短语的方法,比方说:“HELLO STACK”。然后,它必须将每个字母与字母表进行比较,如下所示:
H == 一个?没有。
H == 乙?没有。
...
H==H?是的
然后,searchResult[0] = 7,因为 phrase[i] 中的字母 H 等于 alphabet[7]。现在它找到了字母 H,它应该继续寻找字母 E,依此类推。
不幸的是,我的代码是这样做的:
H == 一个?没有。
E == 乙?没有。
大号 == 小号?没有。
大号 == 大号?没有。
O == E?没有。
(空格) == F?没有。
S == G?没有。
它一直持续到完成短语“HELLO STACK”。如果在字母表中找不到下一个字母,我该怎么做才能阻止它进入下一个字母?
非常感谢!
最佳答案
如果我明白你想做什么,代码应该是:
void searchPhrase(String[] phrase){
searchResult = new int[phrase.length];
int j=0;
for (int i=0; i<frase.length;i++){
for (int k=0; k<alphabet.length;k++){
if (!phrase[i].equals(alphabet[k])){
System.out.println("\nLetter "+phrase[i]+" was not found when comparing it to "+alphabet[k]);
k++;
}
else{
System.out.println("\nLetter "+phrase[i]+" was found when comparing it to "+alphabet[k]);
searchResult[j] = i;
k=0;
break;
}
}
}
}
我还没有测试代码,但它应该可以工作。
关于java - 报告短语中所有字符与字母表中所有字符的匹配状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25597683/