java - Java - 如何使用BufferedReader獲取interger

111 4

我在寫一個小程序,遇到一個問題。

我希望能夠在控制台中鍵入數字,並提取變數的數字,


int aNumber = Integer.parseInt(br.readLine());



類似於這樣的工作:


void Test() {


 while (true) {


 try {


 aNumber = Integer.parseInt(br.readLine());


 } catch (IOException e) {


 e.printStackTrace();


 }


 if (aNumber >= 1) {


 System.out.println("Hurray you enterd a number! It is" + aNumber +".");


 return;


 } else {


 System.out.println("Error: Something went wrong. Please try again.n");


 }


 }


}



如果輸入一個數字,它就能正常工作,

时间: 原作者:

147 4

這樣可以工作,我希望你能理解這個方案,如果解析失敗,Integer.parseInt()將引發NumberFormatException


void test() {


 while (true) {


 int aNumber;


 try {


 aNumber = Integer.parseInt(br.readLine());


 System.out.println("Hurray you enterd a number! It is" + aNumber +".");


 return;


 } catch (NumberFormatException | IOException e) {


 System.out.println("Error: Something went wrong. Please try again.n");


 return;


 }


 }


 }



原作者:
50 3

你的代碼不起作用,因為輸入字元串或其他類型除了int,生成一個NumberFormatException,並且你沒有捕獲它。

if 語句是不必要的,因為只有在給定文本時,catch塊才會被執行,

請check這個代碼


void Test() {


 while (true) {


 try {


 aNumber = Integer.parseInt(br.readLine());


 System.out.println("Hurray you enterd a number! It is" + aNumber +".");


 return;


 } catch (NumberFormatException | IOException e) {


 e.printStackTrace();


 System.out.println("Error: Something went wrong. Please try again.n");


 }


 }


}



原作者:
54 3

最簡單的方法是捕獲NumberFormatException,然後列印你想要的消息。

請參見下面可工作的示例:


import java.io.BufferedReader;


import java.io.IOException;


import java.io.InputStreamReader;



public class ReadNumber {



 public static void main(String[] args) {


 int aNumber = 0;



 while (true) {


 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));


 try {


 aNumber = Integer.parseInt(br.readLine());


 } catch (NumberFormatException e) {


 System.out.println("That wasn't a number.");


 continue;


 } catch (IOException e) {


 e.printStackTrace();


 }


 if (aNumber >= 1) {


 System.out.println("Hurray you entered a number! It is" + aNumber +".");


 continue;


 } else {


 System.out.println("Error: Something went wrong. Please try again.n");


 }


 }


 }


}



原作者:
...