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

时间:2016-04-06 22:07:01

标签: java arrays nullpointerexception

我遇到了这些问题:

  

java.lang.NumberFormatException:对于输入字符串:""
  线程" main"中的例外情况java.lang.NullPointerException

https://api.push.apple.com/

这就是我如何读取数组的值:

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];

这就是我调用方法并将数组作为参数发送的方法

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

这是我的类中加载数组的方法:

obj.asignar(n); 

1 个答案:

答案 0 :(得分:2)

您无法从 String获取整数:

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

但您可以使用两种常用方法:

  1. 跳过 String

    String line = br.readLine();
    if ( !"".equals(line)) {
        x = Integer.parseInt(line);
    }
    
  2. 对空字符串使用默认值 - 如0

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

    您还可以通过编写新方法来概括此方法:

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

    可以使用:

    调用
    x = parseInt(br.readLine(), 0);
    
  3. 与您的评论相关,您可以轻松阅读所需的元素。只需定义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));
    }
    

    例如:

    如果你的输入是

    1
    2
    3
    

    输出将是

    [1, 2, 3]
    
相关问题