我正在尝试编写一个程序来读取包含单词列表的文件,并告诉用户该单词是否是回文。这段代码哪里出错了?输出说它们都是回文,但事实并非如此。
我尝试更改循环。我开始认为这可能是 while 循环,但我需要它来扫描文件。
File file = new File("dictionary.txt");
Scanner INPUT = new Scanner(file);
while (INPUT.hasNextLine()) {
String forward = INPUT.nextLine(); String reverseText = forward;
for(int i = forward.length() - 1; i >= 0; i--)
reverseText += forward.charAt(i);
if (reverseText.equals(forward))
System.out.println(forward + " is a palindrome");
else
System.out.println(forward + " is not a palindrome");
}
我看过一些YouTube视频,读了很多代码片段。我是Java的新手,但似乎回文代码是正确的。那么,文件的读取是问题所在吗?
你的代码可以修复,但我认为这是一个糟糕的算法,应该被替换。 您的空间效率低下,因为您不需要创建整个反向字符串。 而且你的时间效率低下,因为一旦出现字母不匹配,这个词就不是palidrome,所有进一步的处理都是浪费时间。 相反,请考虑:
File file = new File("dictionary.txt");
Scanner input = new Scanner(file);
outer: while (input.hasNextLine())
{
String word = input.nextLine().toLowerCase().trim();
for (int i = 0, j = word.length() - 1; j > i; i++, j--)
{
if (word.charAt(i) != word.charAt(j))
{
System.out.println(word + " is not a palindrome");
continue outer;
}
}
System.out.println(word + " is a palindrome");
}
您需要将第一个变量设置为空字符串,然后添加到其中。此外,您需要将输入字符串设置为小写,否则等于比较将考虑大写字符(即 Redder ≠ reddeR(。要考虑的另一件事是删除空格(字符串末尾的空格和制表符(,因为它会破坏比较。
File file = new File("dictionary.txt");
Scanner INPUT = new Scanner(file);
while (INPUT.hasNextLine()) {
String forward = INPUT.nextLine().toLowerCase().trim();
String reverseText = "";
for(int i = forward.length() - 1; i >= 0; i--)
reverseText += forward.charAt(i);
if (reverseText.equals(forward))
System.out.println(forward + " is a palindrome");
else
System.out.println(forward + " is not a palindrome");
}