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

时间:2018-04-08 08:50:26

标签: java integer

即使我已将其解析为整数值,我仍然会收到错误。我需要从String输入中获取整数值,我删除逗号和空格,并将其存储在数组中,然后将该数组转换为整数数组

import java.util.ArrayList;
import java.util.Scanner; 

public class SeriesSolution {

    public static void main(String[] args) {
         Scanner sc = new Scanner(System.in);
         int count = sc.nextInt();
         ArrayList<Integer> modes = new ArrayList<>();
         for (int x = 0; x < count; x++) {
             String lines = sc.nextLine();
             String[] strs = lines.split(", ");
             int[] array = new int[strs.length];
             for (int i = 0; i < strs.length; i++) {
                 if (Integer.parseInt(strs[i]) > 0 && Integer.parseInt(strs[i]) < 100) {
                     array[i] = Integer.parseInt(strs[i]);

                 }
             }
             modes.add(mode(array));
         }
         for (int y:modes){
             System.out.println(y);
         }
     }

     private static int mode(int a[]) {
         int maxValue=0, maxCount=0;

         for (int anA : a) {
             int count = 0;
             for (int anA1 : a) {
                 if (anA1 == anA) ++count;
             }
             if (count > maxCount) {
                 maxCount = count;
                 maxValue = anA;
             }
         }
         return maxValue;
     }
}

2 个答案:

答案 0 :(得分:0)

在parseInt之前进行检查

if (strs[i] != null && !"".equals(strs[i]) && Integer.parseInt(strs[i])  ...

或者用try catch包围它以捕获在插入字符串而不是数字时将发生的NumberformatException

答案 1 :(得分:0)

问题主要是因为Scanner接受Enter次按键作为输入。因此

String lines = sc.nextLine();

这个代码片段将空字符串存储到lines变量中。传递给NumberFormatException时,此空字符串会抛出parseInt()

我建议您将BufferedReaderInputStreamReader一起使用

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

这适用于较大的输入并且没有错误。虽然预防更好,但必须进行空检查。

如果您想使用Scanner,我建议您更新代码并使用以下代码段。

String lines = "";
while (lines.equals("")) {
    lines = sc.nextLine();
}