将字符串格式的数字转换为整数格式(Java)



我有一个小问题:

import java.io.*;
public class Ninteri {
public static void main(String[] args) throws IOException {
FileReader f = new FileReader("/Users/MyUser/Desktop/reader.txt");
BufferedReader b = new BufferedReader(f);
String s;
int x;
while (true) {
s = b.readLine();
if (s == null) {
break;
}
x = Integer.parseInt(s);
System.out.println(x);
}
}
}

例外:

Exception in thread "main" java.lang.NumberFormatException: For input string: "1 2 3 4 5 6 7 8 "
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at stream.Ninteri.main(Ninteri.java:22)

从错误中可以清楚地看出,文件中的第一行是1 2 3 4 5 6 7 8,它本身不是数字字符串;而是包含数字字符串的字符串。首先,您需要将这一行拆分为一个数字字符串数组,然后您需要迭代该数组,并将数组中的每个元素解析为int

while (true) {
s = b.readLine();
if (s == null) {
break;
}
String[] arr = s.split("\s+");// Split the line on space(s)
for (String num : arr) {
x = Integer.parseInt(num);
System.out.println(x);
}
}

1 2 3 4 5 6 7 8不是单个数字,因此不能用整数表示。

在拆分后得到的字符串数组上使用for块,以分别转换它们中的每一个。

for(String a: s.split("\s")) {
int x = Integer.parseInt(a);
System.out.println(x);
}