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


 }


 }


 }


}



原作者:
...