簡體   English   中英

用Java輸入用戶輸入

[英]Taking User Input in Java

我正在創建一個程序來檢查單詞或短語是否是回文。 我找到了實際的“回文測試儀”。 我堅持的是在我的代碼中放置什么以及讓控制台讀出“輸入回文......”然后發短信。 我已嘗試使用IO,但它無法正常工作。 另外,我如何創建一個循環繼續前進? 這段代碼只允許一次`public class Palindrome {

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

}

要閱讀文本,您需要使用Scanner類,例如:

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

顯然,你的相關代碼在中間。

不是真正的答案,因為它已經給出(因此CW),但我無法抗拒(重新)編寫isPalindrome()方法;)

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

另一個常見的習慣用法是將測試包裝在一個方法中:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM