我有点失落,需要一些帮助。我希望这个程序测试文件中的字符串是否是回文。问题我主要有一个问题是第二个for循环。如果有人能告诉我我错过了什么,我将不胜感激。
public static void main (String args []) throws IOException
{
File file = new File ("Palindromes.txt");
Scanner fileInput = new Scanner (file);
String [] fileArray = new String [20];
String [] arrayClean = new String [20];
char c1, c2;
boolean palindromeTest = false;
int numLines = 0;
while (fileInput.hasNext())
{
fileArray[numLines] = fileInput.nextLine();
numLines++;
}
fileInput.close();
for (int j = 0; j < fileArray.length; j++)
{
arrayClean[j] = fileArray[j];
if (palindromeTest == true)
{
System.out.println (fileArray[j] + " is a palindrome.");
}
if (palindromeTest == false)
{
System.out.println (fileArray [j] + " is not a palindrome.");
}
for (int k = 0; k < arrayClean.length / 2; k++)
{
c1 = fileArray.charAt(arrayClean.length - k - 1);
c2 = fileArray.charAt(k);
if (c2 == c1)
{
palindromeTest = true;
}
else
{
palindromeTest = false;
}
}
}
}
答案 0 :(得分:1)
当任何字符对不同时,测试本身应该说false
;一旦你确定它不同,它就不应该再转向true
了。所以你要这样做(伪代码):
set palindrome to true-so-far
loop for half the characters
if character pair does not match,
it's not a palindrome after all,
and we can stop testing
now we know whether it's still a palindrome, or not a palindrome after all,
so print the result
arrayClean
是不必要的,您可以使用fileArray
fileArray
是不必要的,您可以在一个循环中完成所有操作,通过读取一行然后测试它
前两个是错误;第二个是改进。
答案 1 :(得分:1)
循环遍历字符串的前半部分并确保它以相反的顺序与后半部分匹配:
public static boolean isPalindrome(String str) {
for(int i = 0; i < str.length()/2; i++) {
if(str.charAt(i) != str.charAt(str.length()-i)) return false;
}
return true;
}
并将第二个循环替换为仅检查
if(isPalindrome(fileArray[j])) {
System.out.println (fileArray[j] + " is a palindrome.");
}else{
System.out.println (fileArray[j] + " is not a palindrome.");
}