2013-02-10 87 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