[英]java - Exception in thread “main” java.lang.NumberFormatException: For input string: “” at
[英]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 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));
}
}
也許嘗試在Scanner.nextLine()之后使用.trim()。
String[] arItems = scanner.nextLine().trim().split(" ");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.