简体   繁体   English

回文和数组,挫折中的努力

[英]Palindromes and Arrays, an effort in frustration

I am currently attempting to make a Palindrome Checker using a series of Clean and dirty arrays and while I've gotten it to compile but I'm having issues getting the code to detect the actual palindromes我目前正在尝试使用一系列干净和脏数组来制作回文检查器,虽然我已经编译了它,但是我在获取代码以检测实际回文时遇到了问题

Below is the code in question, any and all help would be most appreciated.以下是有问题的代码,任何和所有帮助都将不胜感激。

    import java.io.*;
import java.util.Scanner;
public class palindrome
{
    public static void main (String[] args) throws IOException
    {
        File inputFile = new File ("Palindromes.txt");

        Scanner inputScan = new Scanner (inputFile);

        String [] dirty = new String [20];

        int i = 0;

        while (inputScan.hasNext())
        {
            dirty[i] = inputScan.nextLine();
            System.out.println(dirty[i]);
            i++;
        }
        inputScan.close();
        String [] clean = new String [i];
        String reverse ="";
        for (int x = 0; x < clean.length; x++)
        {
            clean[x] = "";
            for (int z = length; z < dirty[x].length(); z--)
            {               
                char test = dirty[x].charAt(z);
                if (Character.isLetterOrDigit(test))
                {
                    test = Character.toLowerCase(test);
                    clean [x] += test;
                    if (clean[x].equals(clean[z]))
                    {
                        System.out.println(clean[z] +" is a palindrome");
                    } else
                    {
                        System.out.println(clean[z] +" is NOT a palindrome");
                    }
                }
            }
        }
        for (int j = 0; j < clean.length; j++)
        {
            System.out.println(clean[j]);
        }
    }

Are you trying to do something like this?你想做这样的事情吗?

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class Palindrome {

    public static boolean isPalindrome(String s) {
        s = s.toLowerCase().replaceAll("[\\s\\p{Punct}]", "");
        int len = s.length(), mid = len / 2;
        for (int x = 0; x < mid; x++)
            if (s.charAt(x) != s.charAt(len - x - 1))
                return false;
        return true;
    }

    public static void main(String[] args) throws IOException {
        File inputFile = new File("Palindromes.txt");
        try (Scanner scanner = new Scanner(inputFile)) {
            while (scanner.hasNextLine()) {
                String s = scanner.nextLine();
                if (isPalindrome(s)) {
                    System.out.println(s + " is a palindrome");
                } else {
                    System.out.println(s + " is NOT a palindrome");
                }
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM