Read Data From Text File And Sum Numbers

2019-01-29 04:12发布

I want to read in data from a text file which is full of integers and have the program print those integers out to the screen while summing them. This shouldn't be hard, but I can't figure it out!!!

Here is the extremely simplified text file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

And here is my code that is supposed to work:

import java.util.*;
import java.io.File;
import java.io.IOException;

public class ReadFile
{
    public static void main(String[] args)
    throws IOException
    {
        Scanner textfile = new Scanner(new File("Some_Numbers.txt"));

        filereader(textfile);
    }   


    static void filereader(Scanner textfile)
    {
        int i = 0;
        int sum = 0;

        while(i <= 19)
        {
            System.out.println(textfile.nextInt());
            sum = sum + textfile.nextInt();
            i++;
        }
    }



}

Finally, here is the output I get:

1
3
5
7
9
11
13
15
17
19
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:838)
    at java.util.Scanner.next(Scanner.java:1461)
    at java.util.Scanner.nextInt(Scanner.java:2091)
    at java.util.Scanner.nextInt(Scanner.java:2050)
    at ReadFile.filereader(ReadFile.java:23)
    at ReadFile.main(ReadFile.java:12)

8条回答
来,给爷笑一个
2楼-- · 2019-01-29 04:35

It throws an exception because you don't increment i in the loop. In case if the number of integers in the input file is unknown, you can use the Scanner.hasNextInt() method to check the presence of the next integer (or just use hasNext() to check for EOF).

You can sum the numbers like in the code snippet below:

    ...
    int sum = 0;
    while(i++ < 25)
    {
        sum += aScanner.nextInt();
    }

or

    ...
    int sum = 0;
    while(aScanner.hasNextInt())
    {
        sum += aScanner.nextInt();
    }
查看更多
萌系小妹纸
3楼-- · 2019-01-29 04:46

You are getting the error (exception) because your file has very big numbers that do not fit on Integer types. You should use Long.

So, use: aScanner.nextLong() instead of aScanner.nextInt().

EDIT: You should also change the type of the sum variable from int to long.

Your code will work fine.

查看更多
登录 后发表回答