递归回文

时间:2013-02-10 16:20:45

标签: java

首先,我并没有告诉任何人“做我的功课”。我只需要一些关于如何继续重复过程的帮助。这是我在下面做的程序,它有一个测试器类。

班级:

class RecursivePalindrome {
    public static boolean isPal(String s)
    {
        if(s.length() == 0 || s.length() == 1)
            return true;
        if(s.charAt(0) == s.charAt(s.length()-1))
            return isPal(s.substring(1, s.length()-1));
        return false;
    }
}

然后测试者类有主要方法:

public class RecursivePalindromeTester {   
    public static void main(String[] args)
    {
        RecursivePalindrome  Pal = new RecursivePalindrome ();

        boolean quit = true;
        Scanner in = new Scanner(System.in);
        System.out.print("Enter a word to test whether it is a palindrome or not(press quit to end.): ");
        String x = in.nextLine();
        while(quit) {
            boolean itsPal = Pal.isPal(x);
            if(itsPal == true){
                System.out.println(x + " is a palindrome.");
                quit = false;
            }
            else if (x.equals("quit")) {
                quit = false;
            }
            else {
                quit = false;
                System.out.println(x + " is not a palindrome.");
            }
        }
    }
}

该程序查找该信件是否为回文。我得到了所有的计算和内容但是我该怎么做才能不断询问用户的输入,每次用户输入时都会说它是否是Palindrome词。

2 个答案:

答案 0 :(得分:3)

只需移动要求用户输入的行并阅读它:

System.out.print("Enter a word to test whether it is a palindrome or not(press quit to end.): ");
String x = in.nextLine();

... 进入你的循环,例如,在

之后
while (quit) {

...线。


旁注:quit似乎是布尔值的奇怪名称,当true表示您继续时。 : - )

答案 1 :(得分:1)

只需用另一个while循环包裹。

查看 继续 中断 语句。它们对循环很有帮助,这就是你在这里寻找信息的原因。 公共类RecursivePalindromeTester {

public static void main(String[] args) {
        RecursivePalindrome  Pal = new RecursivePalindrome ();

        Scanner in = new Scanner(System.in);
        while(true){
             System.out.print("Enter a word to test whether it is a palindrome or not(press quit to end.): ");
             String x = in.nextLine();
                boolean itsPal = Pal.isPal(x);
                if(itsPal == true){
                    System.out.println(x + " is a palindrome.");
                } else if (x.equals("quit")) {
                    break;
                } else {
                    System.out.println(x + " is not a palindrome.");
                }
        }
    }
}