无需解析字符串的每个字母,您可以将输入拆分成单词数组并分别检查每个单词。
您可以保持循环,但只需要检查是否与
chart at 0处的循环相同
word.length() - 1
这是一个工作示例。请注意,我已经删除了扫描仪部件,以使其在我正在使用的操场上工作。
// This would be de equivalent of your scannerString input = "We love mom she is the best";String[] words = input.split(" ");String output = "";for(int i=0;i<words.length; i++){ String currentWord = words[i]; if(currentWord.charAt(0) == currentWord.charAt(currentWord.length() -1)) { output = currentWord; }}System.out.println(output);您也不再需要
j变量。
你可以在这里测试



