你會如此善良,請幫助我嗎?我在做一個簡單的問答遊戲,在遊戲中用戶被要求輸入他的答案。它要麼A,B或C.我想這個覆蓋了try/catch的例外...除了使用異常的字符串外,我怎樣才能讀取其他內容?
我想要這個代碼做的,是拋出異常(強制用戶再次輸入答案)每當他會輸入其他字符串。 這裏是一個代碼
Scanner sc = new Scanner(System.in);
String answer = "";
boolean invalidInput = true;
while(invalidInput){
try {
answer = sc.nextLine().toUpperCase();
invalidInput = false;
}
catch(InputMismatchException e){
System.out.println("Enter a letter please");
invalidInput = true;
}
}
現在的問題是,如果我輸入一個整數,它不會扔東西的一部分。
感謝
如何使用
regex
有關讀取字符而不是整數,並且過濾字符代碼?像這樣的東西。 http://stackoverflow.com/questions/4945695/how-to-filter-string-for-unwanted-characters-using-regex或http://stackoverflow.com/questions/13012871/converting-ascii-code-to- char-in-java – Nagarz@Nagarz你的評論應該是一個答案;-) – LionC
@LionC也許,但它不是一個答案,而是一個想法,因爲這不是他要求的。 – Nagarz