【问题标题】:Palindromes and Arrays, an effort in frustration回文和数组,挫折中的努力
【发布时间】:2015-11-19 03:18:38
【问题描述】:

我目前正在尝试使用一系列干净和脏数组制作回文检查器,虽然我已经编译它,但在获取代码以检测实际回文时遇到问题

以下是有问题的代码,我们将不胜感激。

    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]);
        }
    }

【问题讨论】:

  • 编写一个方法来测试回文属性。而且你目前的做法似乎很奇怪。

标签: java arrays for-loop while-loop palindrome


【解决方案1】:

您是否正在尝试做这样的事情?

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

【讨论】:

  • 是的,这就是我要找的,但是我需要将文件输入分成两个单独的数组;一个简单地从文件中读取代码的“脏”数组和一个删除任何标点符号、间距和区分大小写的“干净”数组。有什么办法可以将这些数组实现到这段代码中?
  • @MaxGrant 我编辑了答案以从字符串中删除所有标点符号、间距和区分大小写。
猜你喜欢
  • 2011-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-05
  • 1970-01-01
  • 2011-09-02
  • 1970-01-01
相关资源
最近更新 更多