首页 > 解决方案 > 单词生成器中无限循环文本的问题

问题描述

我正在制作一个回文发生器。基本上,用户输入一个单词或句子,程序输出它是否是回文,这是一个正向和反向拼写相同的单词,如“wow”或“racecar”。我的程序运行良好,但是输出文本会重复 50 次,我似乎无法弄清楚问题出在哪里,而不会把所有事情都搞砸。帮助将不胜感激。


import javax.swing.JOptionPane;

public class palindromedectector {
    public static void main(String[] args) {
        
        String testStrings = "";
           testStrings = JOptionPane.showInputDialog("Enter word: ");
        
    for (int i = 0; i < testStrings.length(); i++)
    {
        System.out.print("\"" + testStrings + "\"");
        if (isPalindrome(stripString(testStrings)))
        System.out.println(" is a palindrome.");
        else
        System.out.println(" is not a palindrome.");
    }   
}

    public static String stripString(String strip)
    {
        strip = strip.toUpperCase();
        String stripped= "";
        for (int i= 0; i< strip.length(); i++)
        {
        if (Character.isLetter(strip.charAt(i)))
            stripped += strip.charAt(i);
        }
        return stripped;
        }
    
    
    public static boolean isPalindrome (String str)
    {
        boolean status = false;
        if (str.length() <= 1)
            status = true;
        else if (str.charAt(0) == str.charAt(str.length()-1))
        {
            status = isPalindrome (str.substring(1, str.length()-1));
        }
        return status;
    }
    }
    



标签: java

解决方案


主要问题是您isPalindrome在循环中运行检查相同的字符串,可能您想运行多个检查

public static void main(String[] args) {

    final int attempts = 5;
    for (int i = 0; i < attempts; i++) {
        String word = JOptionPane.showInputDialog("Enter word: ");

        System.out.print("\"" + word + "\"");
        if (isPalindrome(stripString(word))) {
            System.out.println(" is a palindrome.");
        } else {
            System.out.println(" is not a palindrome.");
        }
    }
}

此外,主要功能可以以更短的方式实现:

// use regexp to get rid of non-letters
private static String stripString(String word) {
    if (null == word || word.isEmpty()) {
        return word;
    }
    return word.replaceAll("[^A-Za-z]", "").toUpperCase(); // remove all non-letters
}

// use Java Stream API to check letters using half of word length
private static boolean isPalindrome(String word) {
    if (null == word) {
        return false;
    }
    final int len = word.length();
    if (len < 2) {
        return true;
    }
    return IntStream.range(0, len/2)
                    .allMatch(i -> word.charAt(i) == word.charAt(len - 1 - i));
}

推荐阅读