这是从老师给我们的单词库中提取的,我应该返回最长的单词,该单词仅包含键盘顶行中的字符。目前它返回空白。请帮忙。
//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;
}