读取包含整数的文本文件到int[]时出现NumberFormatException。

huangapple go评论64阅读模式
英文:

NumberFormatException when I try to read text file of integers into a int[]

问题

我非常困惑。我正在尝试将文本文件中的 10 个整数(每行一个)读入一个 int[] 数组中。我尝试了几种不同的方法,但我最近的尝试是使用 for 循环,并对文件的每一行使用 BufferedReader.readLine() 和 parseInt。但每次都会返回一个 NumberFormatException 异常。

public class InversionCounter {

    static int[] fileToArray(String filename) {
        File file = new File(filename);
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            int numOfLine = Integer.parseInt(br.readLine());
            int[] ourArray = new int[10];

            for (int i = 0; i < ourArray.length; i++) {
                ourArray[i] = numOfLine;
                numOfLine = Integer.parseInt(br.readLine());
            }

            return ourArray;

        } catch (NumberFormatException e) {
            System.out.println("NumberFormatException");
        } catch (FileNotFoundException e) {
            System.out.println("File not found");
        } catch (IOException e) {
            System.out.println("IO Exception");
        }

        return null;
    }

    public static void main(String[] args) throws IOException {
        fileToArray("/home/paris/coolfile");
    }
}

错误信息:

Exception in thread "main" java.lang.NumberFormatException: null
	at java.base/java.lang.Integer.parseInt(Integer.java:614)
	at java.base/java.lang.Integer.parseInt(Integer.java:770)
	at InversionCounter.fileToArray(InversionCounter.java:16)
	at InversionCounter.main(InversionCounter.java:30)

文件内容如下:

45
67
87
76
7
4
5
23
5675
3
英文:

I am very confused. I am trying to get 10 integers on 10 lines of a text file into an int[]. I have tried a few different ways, but my latest attempt is to use a for loop and parseInt on the BufferedReader.readLine() for each line of the file. This is returning a NumberFormatException every time.


public class InversionCounter {

    static int[] fileToArray(String filename) {
        File file = new File(filename);
        try ( BufferedReader br = new BufferedReader(new FileReader(file))) {
        int numOfLine = Integer.parseInt(br.readLine());
        int[] ourArray = new int[10];

        for (int i = 0; i &lt; ourArray.length; i++)  {
            ourArray[i] = numOfLine;
            numOfLine = Integer.parseInt(br.readLine());
        }


        return ourArray;

        }  catch (NumberFormatException e) {
        System.out.println(&quot;NumberFormatException&quot;);
        } catch (FileNotFoundException e) {
            System.out.println(&quot;File not found&quot;);
        } catch (IOException e) {
            System.out.println(&quot;IO Exception&quot;);
        }

        return null;
    }

    public static void main(String[] args) throws IOException {
        fileToArray(&quot;/home/paris/coolfile&quot;);

    }



        }

Error:

Exception in thread &quot;main&quot; java.lang.NumberFormatException: null
	at java.base/java.lang.Integer.parseInt(Integer.java:614)
	at java.base/java.lang.Integer.parseInt(Integer.java:770)
	at InversionCounter.fileToArray(InversionCounter.java:16)
	at InversionCounter.main(InversionCounter.java:30)

The file is simply this:

45
67
87
76
7
4
5
23
5675
3

答案1

得分: 1

问题出在文件的这一行被读取时:

int numOfLine = Integer.parseInt(br.readLine());

引用 BufferedReader.readLine() 的Javadoc:

>返回:包含行内容(不包括任何行终止字符)的字符串,如果在未读取任何字符的情况下已到达流的末尾,则返回null

您需要在解析之前测试读取的行是否为null,否则 Integer.parseInt() 将会抛出 NumberFormatException

这是一个简单的修复方法:

String line = br.readLine();
if (line == null) {
    break;
}
int numOfLine = Integer.parseInt(line);

一个更好的方法是不假设一定数量的输入,而只需持续读取行直到文件末尾(即直到行为null),并将它们添加到 List<Integer> 中。

英文:

The problem occurs when the line of the file has been read here:

int numOfLine = Integer.parseInt(br.readLine());

Quoting the javadoc of BufferedReader.readLine()

>Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached without reading any characters.

You need to test if the line read is null before parsing it, otherwise Integer.parseInt() will throw a NumberFormatException.

This is a simple fix:

String line = br.readLine();
if (line == null) {
    break;
}
int numOfLine = Integer.parseInt(line);

A better approach is to not assume a certain quantity of input and just keep reading lines until the end of file (ie until line is null), adding them to a List&lt;Integer&gt;.

答案2

得分: 1

以下是翻译好的部分:

只有文件中有10行,但你的readLine指针正尝试读取第11行。这是因为你在循环外读取了一行,现在尝试在循环中读取10行。以下代码应该可以工作:

public class InversionCounter {
    static int[] fileToArray(String filename) {
        File file = new File(filename);
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            int numOfLine = Integer.parseInt(br.readLine());
            int[] ourArray = new int[10];

            for (int i = 0; i < (ourArray.length - 1); i++) {
                ourArray[i] = numOfLine;
                numOfLine = Integer.parseInt(br.readLine());
            }

            return ourArray;

        } catch (NumberFormatException e) {
            System.out.println("NumberFormatException");
        } catch (FileNotFoundException e) {
            System.out.println("File not found");
        } catch (IOException e) {
            System.out.println("IO Exception");
        }

        return null;
    }

    public static void main(String[] args) throws IOException {
        fileToArray("/home/paris/coolfile");
    }
}

附注:还应该修剪行,以防有任何额外的空格。

英文:

There are only 10 lines in the file but your readLine pointer is trying to read 11th line. This is happening because you read one line outside of the loop and now trying to read 10 lines in the loop. Following code should work:

public class InversionCounter {
    static int[] fileToArray(String filename) {
        File file = new File(filename);
        try ( BufferedReader br = new BufferedReader(new FileReader(file))) {
        int numOfLine = Integer.parseInt(br.readLine());
        int[] ourArray = new int[10];

        for (int i = 0; i &lt; (ourArray.length - 1); i++)  {
            ourArray[i] = numOfLine;
            numOfLine = Integer.parseInt(br.readLine());
        }


        return ourArray;

        }  catch (NumberFormatException e) {
        System.out.println(&quot;NumberFormatException&quot;);
        } catch (FileNotFoundException e) {
            System.out.println(&quot;File not found&quot;);
        } catch (IOException e) {
            System.out.println(&quot;IO Exception&quot;);
        }

        return null;
    }

    public static void main(String[] args) throws IOException {
        fileToArray(&quot;/home/paris/coolfile&quot;);

    }


}

P.S: Also, you should trim the line in case if there are any extra spaces.

huangapple
  • 本文由 发表于 2020年9月22日 12:18:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/64003023.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定