Error : Exception in thread "main" java.lang.NumberFormatException: For input string: ""

Error : Exception in thread "main" java.lang.NumberFormatException: For input string: ""

我正在尝试将数字作为 string 输入并将它们拆分并存储在 string 数组中,然后将它们作为整数存储在 int 数组中。我已经尝试了很多东西,比如 .trim()scanner.skip() 但我无法在这里解决这个问题。

我的输入:

4 
1 2 2 2

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

    Scanner scanner = new Scanner(System.in);
    int arCount = scanner.nextInt();
    int[] ar = new int[arCount];
    String[] arItems = scanner.nextLine().split(" ");

    for (int i = 0; i < arCount; i++) {
        int arItem = Integer.parseInt(arItems[i].trim());
        ar[i] = arItem;
    }
    scanner.close();
 }

收到的错误是:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at Hello.main(Hello.java:32)

也许尝试在 Scanner.nextLine() 之后使用 .trim()。

String[] arItems = scanner.nextLine().trim().split(" ");

您可以捕获异常并跳过错误记录。

我还建议您拆分一个或多个空格以防止空字符串开头

Scanner scanner = new Scanner(System.in);
int arCount = scanner.nextInt();
scanner.nextLine();
int[] ar = new int[arCount];
String[] arItems = scanner.nextLine().split("\s+");

for (int i = 0; i < arCount; i++) {
    try {
        ar[i] = Integer.parseInt(arItems[i].trim());
    } catch (NumberFormatException e) {
        System.err.println(arItems[i] + " is not an int");
    }
}

你为什么不一遍又一遍地使用 nextInt() 方法(完全绕过 split 的使用),就像这样,

import java.util.*;

public class MyClass {
    public static void main(String []args){

    Scanner scanner = new Scanner(System.in);
    int arCount = scanner.nextInt();

    int[] ar = new int[arCount];
    for(int i=0;i<arCount;i++){
        ar[i] = scanner.nextInt();;
    }
    System.out.println(Arrays.toString(ar));

    scanner.close();
 }
}

更新:

在您的原始程序中,您首先使用 nextInt() 方法,该方法不使用换行符 '\n'。因此,下一次调用 nextLine() 实际上会使用同一行的换行符,而不是包含数组整数的下一行。所以,为了让你的代码正常工作,你可以稍微修改一下,

import java.util.*;

public class MyClass {
    public static void main(String []args){

    Scanner scanner = new Scanner(System.in);
    int arCount = scanner.nextInt(); // doesn't consume \n
    int[] ar = new int[arCount];
    scanner.nextLine(); //consumes \n on same line 
    String line = scanner.nextLine(); // line is the string containing array numbers
    System.out.println(line);
    String[] arItems = line.trim().split(" "); //trim the line first, just in case there are extra spaces somewhere in the input
    System.out.println(Arrays.toString(arItems));
    for (int i = 0; i < arCount; i++) {
        int arItem = Integer.parseInt(arItems[i].trim());
        ar[i] = arItem;
    }
    System.out.println(Arrays.toString(arItems));
 }
}