我一直在嘗試將用戶字符串輸入轉換爲int的不同方法,我可以比較並構建「if-then」語句。每次我嘗試測試它時,它都會拋出異常。任何人都可以看看我的Java代碼並幫助我找到方法嗎?我對此毫無頭緒(在編程中也是一個noob)。如果我打破任何規則,請讓我知道我是新來的。謝謝。將用戶輸入的字符串轉換爲數字(整數)值。
總之,這裏是代碼:
System.out.println("Sorry couldn't find your user profile " + userName + ".");
System.out.println("Would you like to create a new user profile now? (Enter Y for yes), (Enter N for no and exit).");
try {
BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
Character i = new Character(addNewUser.charAt(0));
String s = i.toString();
int answerInDecimal = Integer.parseInt(s);
System.out.println(answerInDecimal);
}
catch(Exception e) {
System.out.println("You've mistyped the answer.");
e.getMessage();
}
您的輸入是什麼?什麼是異常堆棧跟蹤? – Atreys
請發佈堆棧跟蹤 - – antlersoft
只是一個側面的建議,您可以使用'String s = addNewUser.substring(0,1)'獲取第一個字符作爲字符串。 –