Home > Software engineering >  How to sum up all ints in a text file?
How to sum up all ints in a text file?

Time:03-10

I need to pull integers from a text file and sum them up. I came up with this but I keep getting an error. What am I missing? I need to use a scanner class.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class txtClass {

    public static void main(String[] args) throws FileNotFoundException {
        
        File txtFile = new File(//text file path//);
        Scanner scan = new Scanner(txtFile);
        
        int length = 0;
        while(scan.hasNextLine()) {
            scan.nextLine();
            length  ;
        }
        
        
        int array[] = new int [length];
        array[length  ] = scan.nextInt();
        
        System.out.println(array.toString());
        int h = 0;
        
        for (int i = 0; i<array.length; i  )
        {
            h  =array[i];   
        }
        scan.close();
        System.out.print(h);
    }

}

CodePudding user response:

As suggested, a lot of the code is not really needed. But presumably the 'error' you get is array index out of bounds. Here:

    int array[] = new int [length];
    array[length  ] = scan.nextInt();

So you allocate an array and immediately access off the end of the array. Let's assume length is 42. Therefore, the allocated array elements have indexes 0 to 41. You try and assign something to array[42]. I'm not sure what you're trying to do with that line.

The alternative guess (which we would not need to guess had you mentioned the actual error message) is that your counting lines leaves the scanner positioned at end of file. so the scan.nextInt() call in the assignment gets you an I/O error.

In any case, the core of the solution is something like

int sum = 0;
while (scan.hasNextInt())
   sum  = scan.nextInt();

No array is needed.

CodePudding user response:

Can you give some information about when the error occurs? I think instead of using an array to store the numbers before adding it would be easier to add the numbers as you go. I think the error might be occurring because you have scanned the whole document to get the length and when you try to scan.nextInt you are already at the end of the document.

  • Related