Java 如何在使用BufferedReader时避免NumberFormatException?

Java 如何在使用BufferedReader时避免NumberFormatException?,java,c,io,bufferedreader,Java,C,Io,Bufferedreader,我使用BufferedReader从用户处读取数据,但它会给出NumberFormat异常,只要我以某种方式给出输入。假设在C中,我编写如下代码: scanf("%d %d", &x, &y); 我试着给控制台这样的输入:2345,它赋值如下: scanf("%d %d", &x, &y); x=23,y=45 如何在java中执行类似的操作。我试着这样做: BufferedReader br1 = new BufferedReader(new InputSt

我使用BufferedReader从用户处读取数据,但它会给出NumberFormat异常,只要我以某种方式给出输入。假设在C中,我编写如下代码:

scanf("%d %d", &x, &y);
我试着给控制台这样的输入:2345,它赋值如下:

scanf("%d %d", &x, &y);
x=23,y=45

如何在java中执行类似的操作。我试着这样做:

BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in));
String line1 = br1.readLine();
String line2 = br2.readLine();
int x = Integer.parseInt(line1);
int y = Integer.parseInt(line2);
但这给了:

线程主java.lang.NumberFormatException中的异常:用于输入 字符串:23 45 at java.lang.NumberFormatException.forInputStringUnknown源位于 java.lang.Integer.parseIntUnknown源代码位于 java.lang.Integer.parseIntUnknown源代码位于AB.mainAB.java:23


一个InputStreamReader就足够了:

   BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
    String line1 = br1.readLine();
    String[] args = line1.split(" ");

    if (args.length != 2) {
        throw new IllegalArgumentException("The input is wrong");
    }

    int x = getIntFromInput(args[0]);
    int y = getIntFromInput(args[1]);
正如Jan指出的,您需要一种转换方法:

public static int getIntFromInput(String inputString) {

    //sanity checks
    if (inputString == null || inputString.trim().length() == 0) {
        throw new IllegalArgumentException("empty or null string passed");
    }

    try {
        return new BigInteger(inputString, 10).intValueExact();
    } catch (Exception ignored) {
        throw new IllegalArgumentException(String.format("input string is not a valid integer number: '%s'", inputString));
    }
}

一个InputStreamReader就足够了:

   BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
    String line1 = br1.readLine();
    String[] args = line1.split(" ");

    if (args.length != 2) {
        throw new IllegalArgumentException("The input is wrong");
    }

    int x = getIntFromInput(args[0]);
    int y = getIntFromInput(args[1]);
正如Jan指出的,您需要一种转换方法:

public static int getIntFromInput(String inputString) {

    //sanity checks
    if (inputString == null || inputString.trim().length() == 0) {
        throw new IllegalArgumentException("empty or null string passed");
    }

    try {
        return new BigInteger(inputString, 10).intValueExact();
    } catch (Exception ignored) {
        throw new IllegalArgumentException(String.format("input string is not a valid integer number: '%s'", inputString));
    }
}

如果确实要在同一行上传递两个参数,请在空白处拆分该行,然后分别使用每个标记:

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

String line1 = br1.readLine();

String[] tokens = line1.split("\\s+") 

int x = Integer.parseInt(tokens[0]);
int y = Integer.parseInt(tokens[1]);

如果确实要在同一行上传递两个参数,请在空白处拆分该行,然后分别使用每个标记:

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

String line1 = br1.readLine();

String[] tokens = line1.split("\\s+") 

int x = Integer.parseInt(tokens[0]);
int y = Integer.parseInt(tokens[1]);
readLine一直读取,直到出现换行符,这通常意味着用户按下了enter键

如果输入1234,这是一行,一行的格式不是整数

您可以使用read一次读取一个字符,手动拆分行并解析结果,或者最好使用Scanner类。它有一个更面向用户IO的api,公开了一些方法,比如nextInt或next返回下一个令牌而不是next char等等

Scanner in = new Scanner(System.in);
int x = in.nextInt();
int y = in.nextInt();
readLine一直读取,直到出现换行符,这通常意味着用户按下了enter键

如果输入1234,这是一行,一行的格式不是整数

您可以使用read一次读取一个字符,手动拆分行并解析结果,或者最好使用Scanner类。它有一个更面向用户IO的api,公开了一些方法,比如nextInt或next返回下一个令牌而不是next char等等

Scanner in = new Scanner(System.in);
int x = in.nextInt();
int y = in.nextInt();

你必须这样做:

String in = *getline*;
String[] tab = in.split(' ');
List<int> nums = new         ArrayList<int>();

for(String a : tab){
nums.add(Integer.parseInt(a));         // or push() not remember...
}

// Your nums have your integers now

你必须这样做:

String in = *getline*;
String[] tab = in.split(' ');
List<int> nums = new         ArrayList<int>();

for(String a : tab){
nums.add(Integer.parseInt(a));         // or push() not remember...
}

// Your nums have your integers now

这将解决你的目的

int x, y;
String[] input;
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  String str = br.readLine();
  input = str.split(" ");

  x = Integer.parseInt(input[0]);
  y = Integer.parseInt(input[1]);

这将解决你的目的

int x, y;
String[] input;
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  String str = br.readLine();
  input = str.split(" ");

  x = Integer.parseInt(input[0]);
  y = Integer.parseInt(input[1]);

现在我们有很多答案,只是解释如何阅读正确的输入。但你会以任何其他奇怪的方式得到许多形式的概念。如果你的意见是

98765432109876543210 9876543210987654321 
这将反过来引发NumberFormatException,因为它们太大,无法放入int

因此,虽然手动拆分和寻址令牌是一个很好的建议,但如果仅给出一个数字,您也会遇到ArrayIndexOutOfBounds

我的建议是,在进行任何进一步的分析之前,检查输入是否有效:

Scanner s = new Scanner(System.in);
String line = s.nextLine();
Pattern p = Pattern.compile("(\\d{1,10})\\s+(\\d{1,10})");
Matcher m = p.matcher(line);
if(m.matches()) {
  long x1 = Long.parseLong(m.group(1));
  long y1 = Long.parseLong(m.group(2));
  if(x1 <= Integer.MAX_VALUE&& y1 <= Integer.MAX_VALUE) {   
    int x = (int)x1;
    int y = (int)y1;
    System.out.printf("Your input: %d / %d", x, y);
  } else {
    System.err.println("Numbers too big");
  }
} else {
  System.err.println("Input does not match criteria");
}

现在我们有很多答案,只是解释如何阅读正确的输入。但你会以任何其他奇怪的方式得到许多形式的概念。如果你的意见是

98765432109876543210 9876543210987654321 
这将反过来引发NumberFormatException,因为它们太大,无法放入int

因此,虽然手动拆分和寻址令牌是一个很好的建议,但如果仅给出一个数字,您也会遇到ArrayIndexOutOfBounds

我的建议是,在进行任何进一步的分析之前,检查输入是否有效:

Scanner s = new Scanner(System.in);
String line = s.nextLine();
Pattern p = Pattern.compile("(\\d{1,10})\\s+(\\d{1,10})");
Matcher m = p.matcher(line);
if(m.matches()) {
  long x1 = Long.parseLong(m.group(1));
  long y1 = Long.parseLong(m.group(2));
  if(x1 <= Integer.MAX_VALUE&& y1 <= Integer.MAX_VALUE) {   
    int x = (int)x1;
    int y = (int)y1;
    System.out.printf("Your input: %d / %d", x, y);
  } else {
    System.err.println("Numbers too big");
  }
} else {
  System.err.println("Input does not match criteria");
}

您可以从文件中读取数据,并基于一个或多个空间分割字符串,还可以处理多个由空间分隔的输入

        Scanner s = new Scanner(System.in);
        String line = s.nextLine();
        //String line = "98765432109876543210 9876543210987654321   ";
        String[] splited = line.split("\\s+");
然后比较每个字符串以检查它是否为有效数字。 然后根据该数字创建一个新的BigDecimal。内存允许的64位jvm上的BigDecimal最多可容纳6456993位数字

        for (int i=0;i<splited.length;i++) {

            if(splited[i].matches("[0-9]*")){

                BigDecimal num = new BigDecimal(splited[i]);
                System.out.println("num "+(i+1)+"="+num);
            }
        }



 Results
 line ="98765432109876543210 9876543210987654321   "
 num 1=98765432109876543210
 num 2=9876543210987654321

 line ="1212312312312312312312313 123432432432432423432423432"
 num 1=1212312312312312312312313
 num 2=123432432432432423432423432

您可以从文件中读取数据,并基于一个或多个空间分割字符串,还可以处理多个由空间分隔的输入

        Scanner s = new Scanner(System.in);
        String line = s.nextLine();
        //String line = "98765432109876543210 9876543210987654321   ";
        String[] splited = line.split("\\s+");
然后比较每个字符串以检查它是否为有效数字。 然后根据该数字创建一个新的BigDecimal。内存允许的64位jvm上的BigDecimal最多可容纳6456993位数字

        for (int i=0;i<splited.length;i++) {

            if(splited[i].matches("[0-9]*")){

                BigDecimal num = new BigDecimal(splited[i]);
                System.out.println("num "+(i+1)+"="+num);
            }
        }



 Results
 line ="98765432109876543210 9876543210987654321   "
 num 1=98765432109876543210
 num 2=9876543210987654321

 line ="1212312312312312312312313 123432432432432423432423432"
 num 1=1212312312312312312312313
 num 2=123432432432432423432423432

如果我没弄错的话,你写的是一行。试着像这样给它:23输入45如果你想达到这个目标,你必须读一行你想要的所有数字,然后将这个字符串拆分spaces@user3248186它只接受一次输入或请求两次?readLine一直读取到行尾。在这种情况下,它应该问你twice@Greyshack:我知道它作为一行,如果我按enter键,它就可以工作,但我希望它能与空格一起工作,因为在hackerearth等网站上就是这样给出的。是的,我告诉过你,您可以只读取一行,然后使用String的split方法将其拆分,并将其作为拆分的参数传递。如果我没有弄错的话,您所写的内容将被读取为一行。试着像这样给它:23输入45如果你想达到这个目标,你必须读一行你想要的所有数字,然后将这个字符串拆分spaces@user3248186它只接受输入o
一次或请求两次?读线一直读到行尾。在这种情况下,它应该问你twice@Greyshack:我知道它是一行,如果我按enter键,它就可以工作,但我希望它能与空格一起工作,因为在hackerearth这样的网站上是这样给出的。是的,我告诉过你,你只能读一行,然后使用String的split方法将其拆分,并将其作为splittingWell的参数传递。。。它仍然会为输入抛出NumberFormatException,比如1212313123432432432432423432423432@Jan,不会的,不会的;哦,是的。试试看。@Jan,请回顾一下:现在它至少不再抛出numberformatceptions了。。但是非法辩论除外。不确定这有多大帮助:嗯。。。它仍然会为输入抛出NumberFormatException,比如1212313123432432432432423432423432@Jan,不会的,不会的;哦,是的。试试看。@Jan,请回顾一下:现在它至少不再抛出numberformatceptions了。。但是非法辩论除外。不确定这有多大帮助:负数怎么样正当这些数据是否有效无疑问。我在这里是一个乐观主义者,只会看到积极的一面:-那么消极的数字呢正当这些数据是否有效无疑问。我是这里的乐观主义者,只会看到积极的一面:-