這是從我們的老師給我們的單詞庫中拉出來的,我應該返回最長的單詞,其中只包含鍵盤第一行的字符。目前它返回空白。請幫忙。這是爲什麼返回空白?
//What's the longest word only using the top row of the keyboard?
public static void Question6() {
String longestWordSoFar = " ";
System.out.println("Question 6:");
for(int i = 1; i < WordList.numWords(); i++) // check every word in wordlist
{
if(topRow(WordList.word(i))) { // if the length is greater than the previous word, replace it
{
if(WordList.word(i).length() > longestWordSoFar.length())
longestWordSoFar=WordList.word(i);
}
}
}
System.out.println("longest word including top row: " + longestWordSoFar);
System.out.println();
return;
}
public static boolean topRow(String word) {
for(int i = 0; i < word.length(); i++) {
//return true if the word has all of the letters in the top row of the keyboard
if (word.charAt(i) != 'q') {
return false;
}
if (word.charAt(i) != 'w') {
return false;
}
if (word.charAt(i) != 'e') {
return false;
}
if (word.charAt(i) != 'r') {
return false;
}
if (word.charAt(i) != 't') {
return false;
}
if (word.charAt(i) != 'y') {
return false;
}
if (word.charAt(i) != 'u') {
return false;
}
if (word.charAt(i) != 'i') {
return false;
}
if (word.charAt(i) != 'o') {
return false;
}
if (word.charAt(i) != 'p') {
return false;
}
}
return true;
}
您是否試圖調試過您的代碼?同樣,你的邏輯看起來很奇怪,因爲'w'!='q','qwert'這個詞作爲'topRow'參數將在第一次迭代中返回'false'。 –
你最好使用'contains'函數,而不是遍歷每個字符。獲得更好的性能。 'if(!word.contains(「q」))return false;' – Doomsknight