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

问题描述 投票:0回答:1

我有一个小问题。

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:

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)
java integer buffer filereader parseint
1个回答
0
投票

从错误来看,很明显,你的文件中的第一行是 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);
    }
}

0
投票

1 2 3 4 5 6 7 8不是一个单一的数字,所以不能用Integer表示。

在拆分产生的字符串数组上使用for块来分别转换它们。

for(String a: s.split("\\s")) {
    int x = Integer.parseInt(a);
    System.out.println(x);
}
© www.soinside.com 2019 - 2024. All rights reserved.