简体   繁体   English

错误!!! NumberFormatException:对于输入字符串:“”

[英]Error!!! NumberFormatException: For input string: ""

I'm getting these issues:我遇到了这些问题:

java.lang.NumberFormatException: For input string: "" java.lang.NumberFormatException:对于输入字符串:“”
Exception in thread "main" java.lang.NullPointerException线程“main”中的异常 java.lang.NullPointerException

System.out.println("Amount of elements to calculate: ");
try
{
   x = Integer.parseInt(br.readLine()); 
}
catch(NumberFormatException | IOException z)
{
   System.out.println("Error!!!"+z);
}

int [] n = new int[x];

this is how I'm reading the values of the array:这就是我读取数组值的方式:

for(int i=0; i<n.length; i++)
    n[i] = Integer.parseInt(br.readLine()); 

this is how I call the method and send the array as a parameter这就是我调用方法并将数组作为参数发送的方式

obj.asignar(n); 

and this is the method in my class in which I load the array:这是我在类中加载数组的方法:

private int[] num;

public void asignar(int n[])
{

    for(int i=0; i<n.length; i++)
    {
        num[i] = n[i];
    }
}

You cannot get an integer from an empty String :您无法从String获取整数:

Integer.parseInt(br.readLine());   // when br.readLine() is ""

but you can use 2 common approaches:但您可以使用 2 种常用方法:

  1. Skip the empty String s:跳过String s:

     String line = br.readLine(); if ( !"".equals(line)) { x = Integer.parseInt(line); }
  2. Use a default value for the empty String - like 0 :为空字符串使用默认值- 如0

     String line = br.readLine(); x = "".equals(line) ? 0 : Integer.parseInt(line);

    You can also generalize this approach by writing a new method:您还可以通过编写一个新方法来概括这种方法:

     static int parseInt(String s, int defaultValue) { try { return Integer.parseInt(s); } catch (NumberFormatException e) { return defaultValue; } }

    that can be called using:可以使用以下方法调用:

     x = parseInt(br.readLine(), 0);

Related to your comment, it's easy to read as many elements as you want.与您的评论相关,您可以轻松阅读任意数量的元素。 Just define a total and use it in a for loop:只需定义一个total并在for循环中使用它:

public static void main(String[] args) throws IOException {

    int total = 3;
    int n[] = new int[total];
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    for (int i = 0; i < total; i++) {
        n[i] = Integer.parseInt(br.readLine()); // use the approaches above
    }

    System.out.println(Arrays.toString(n));
}

Eg:例如:

If your input is如果您的输入是

1
2
3

the output will be输出将是

[1, 2, 3]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM