2013-02-10 88 views
1

首先我不告诉任何人“做我的功课”。我只需要一点帮助就如何不断重复一个过程。这是我下面做的程序,它有一个测试程序类。递归回文

类:

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

然后具有main方法的类测试仪:

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

此程序发现如果字母是回文或没有。我得到了所有的计算和东西,但我该怎么做才能继续询问用户输入,并且每次用户输入时都会说明它是否是回文单词。

+1

使用一致缩进层次会使你的代码可读性更强 - 给自己和他人。 – 2013-02-10 16:25:39

+0

我将如何放置一个ignoreCase,以便当用户输入时忽略case – user2059140 2013-02-10 16:36:54

+0

@ user2059140: - 您可以使用ToUpper()方法将字符串更改为所有Caps。我的答案也更新了。 – 2013-02-10 16:45:30

回答

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."); 
       } 
     } 
    } 
} 
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,意味着你继续下去一个奇特的名字。 :-)

+0

是的,但如果我把真实的输出将继续重复,但我需要重复每一次的问题,并每次给结果。 – user2059140 2013-02-10 16:27:35

+0

@ user2059140:这就是将这些行移入循环所能实现的。我已经澄清了我在说什么,以及在哪里移动它们。 – 2013-02-10 16:28:10

+0

我做了同样的事情。一旦我按下一个输入,程序显示一个结果,那就结束了。 – user2059140 2013-02-10 16:31:12