我在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 == A?没有。
H == B?没有。
...
H == H?是
然后,由于来自短语[i]的字母H等于字母[7],所以searchResult [0] = 7。既然找到了字母H,就应该继续字母E,依此类推。
不幸的是,我的代码正在这样做:
H == A?没有。
E == B?没有。
L == C?没有。
L == D?没有。
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;
}
}
}
}
我还没有测试代码,但是应该可以。