检查文件中的数组是否为回文

  • 本文关键字:是否 回文 数组 文件 java
  • 更新时间 :
  • 英文 :


我有点迷路了,需要一些帮助。我想让这个程序测试文件中的字符串是否是回文。我主要遇到的问题是第二个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;
            }
        }
    }
}
  • 你首先说一行是否是回文,然后测试它——这样,每一行都将根据前一行的测试进行打印
  • 任何字符对不同时,测试本身应该说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是不必要的,你可以在一个循环中完成所有事情,通过读取一行然后测试它

前两个是错误;第二个是改进。

在字符串的前半部分循环,并确保它以相反的顺序匹配后半部分:

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.");
}

最新更新