這是我在我的代碼無法獲得字符用戶輸入的工作
char guess = Keyboard.readChar();
但錯誤信息出現爲「The method readChar() is undefined for the type scanner
」掃描我已經是Scanner keyboard = new Scanner (System.in)
。爲什麼這是錯的?
這是我在我的代碼無法獲得字符用戶輸入的工作
char guess = Keyboard.readChar();
但錯誤信息出現爲「The method readChar() is undefined for the type scanner
」掃描我已經是Scanner keyboard = new Scanner (System.in)
。爲什麼這是錯的?
你需要使用這個
char guess = keyboard.next().charAt(0);
Scanner
沒有閱讀char
的方法。基本上,System.in
是一個緩衝流。你可以讀一條線,
while(keyboard.hasNextLine()) {
String line = keyboard.nextLine();
char[] chars = line.toCharArray(); // <-- the chars read.
}
你可以嘗試使用nextLine()
讀取字符串的文本。
char code = keyboard.nextLine().charAt(0);
charAt(0)
取得接收到的輸入的第一個字符。
附加說明: 如果要用戶輸入轉換爲大/小寫。這特別有用。
你可以鏈串在一起的方法:
char code1 = keyboard.nextLine().toUpperCase().charAt(0); //Convert input to uppercase
char code2 = keyboard.nextLine().toLowerCase().charAt(0); //Convert input to lowercase
char code3 = keyboard.nextLine().replace(" ", "").charAt(0); //Prevent reading whitespace
見http://stackoverflow.com/questions/13942701/take-a-char-input-from-the-scanner – NaCl 2014-11-01 04:24:53