2010-04-17 141 views
2

我正在創建一個程序來檢查單詞或短語是否是迴文。我有了真正的「迴文測試儀」。我堅持的是在我的代碼中放置什麼以及如何讓控制檯讀出「Enter palindrome ...」然後文本。我已經嘗試過IO,但它沒有正確的工作。另外,我如何創建一個循環繼續前進?此代碼只允許一次一個'公共類迴文{在Java中輸入用戶輸入

public static void main(String args[]) { 
    String s=""; 
    int i; 
    int n=s.length(); 
    String str=""; 

    for(i=n-1;i>=0;i--) 
    str=str+s.charAt(i); 

    if(str.equals(s)) 
    System.out.println(s+ " is a palindrome"); 

    else System.out.println(s+ " is not a palindrome"); } 

} 
+0

在見例如:http://計算器。 com/questions/2622725/how-to-take-user-input-in-array-using-java – polygenelubricants 2010-04-17 03:22:02

+1

問題標題是誤導人的。你沒有迴文問題,但收集用戶輸入。 – BalusC 2010-04-17 03:49:55

回答

7

要在文本閱讀,你需要使用掃描儀類,例如:

import java.util.*; 

public class MyConsoleInput { 

    public static void main(String[] args) { 
     String myInput; 
     Scanner in = new Scanner(System.in); 

     System.out.println("Enter some data: "); 
     myInput = in.nextLine(); 
     in.close(); 

     System.out.println("You entered: " + myInput); 
    } 
} 

應用此概念,然後再進行迴文檢查,然後按照前面的順序進行排序。

至於遍歷允許多張支票,你可以不喜歡提供的關鍵字(如「退出」),然後做一些事情,如:

do { 
    //... 
} while (!myInput.equals("exit")); 

與您相關的代碼在中間,很明顯。

+0

myInput!=「exit」 - 應該使用'!s1.equals(s2)'; 's1!= s2'將不起作用。 – polygenelubricants 2010-04-17 03:00:04

+0

哎呀 - 感謝您指出! – 2010-04-17 09:03:46

0

另一種常見的成語是包裝測試中的方法:

private static boolean isPalindrome(String s) { 
    ... 
    return str.equals(s); 
} 

然後過濾標準輸入,調用isPalindrome()每一行:

public static void main(String[] args) throws IOException { 
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
    String s; 
    while ((s = in.readLine()) != null) { 
     System.out.println(isPalindrome(s) + ": " + s); 
    } 
} 

這可以很容易地檢查一個單線:

echo "madamimadam" | java MyClass

或整個文件:

java MyClass < /usr/share/dict/words
1

不是一個真正的答案,因爲它已經給定(因此CW),但我無法抗拒(重新)寫isPalindrome()方法)

public static boolean isPalindrome(String s) { 
    return new StringBuilder(s).reverse().toString().equals(s); 
} 
+0

是的,但想必這是家庭作業,他們會被禁止做這樣的事情。 – polygenelubricants 2010-04-17 03:58:03

+1

Ach,這是星期五。 – BalusC 2010-04-17 04:30:03