Gorobei Kawazu
Gorobei Kawazu

Reputation: 31

Reading a file of integers, getting nothing but zero

So, in my program I'm supposed to read integers from a text file to make a key-listed array of them. Easy enough, except when I got to read the file I get nothing but zeroes out of it. The file itself looks like this:

10111

86 78 95

20222

81 73 87

30333

71 63 77

40444

62 58 67

50555

51 62 48

And the code I'm currently is:

    File stuff = new File("TheData.txt");
    int [] temp = new int[36];
    int spine =0;
    try {
        Scanner sc = new Scanner(stuff);
        while(sc.hasNextInt()){
                temp[spine++] = sc.nextInt();
                System.out.println("" + temp[spine]);
            }

    } catch (FileNotFoundException ex) {
        Logger.getLogger(ProgramDriver3.class.getName()).log(Level.SEVERE, null, ex);
    }

I'm trying to read the numbers into a temporary array of ints so I can sort them into where they're supposed to go (the long ones are student ids, the short ones are test scores). When I try and run the thing, though, all I get is

run:

0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
BUILD SUCCESSFUL (total time: 1 second)

I'm not entirely certain what's going wrong

Upvotes: 0

Views: 54

Answers (2)

Strikeskids
Strikeskids

Reputation: 4052

You are printing out the number at the index after you have already incremented it. Change your print statement to print out the index without the increment.

System.out.println(temp[spine-1]);

Also, you have set a length on your array independent of the input file. I would use a List so that the number of integers in the file does not cause a ArrayIndexOutOfBoundsException upon reading a file that is too large.

List<Integer> list = new ArrayList<Integer>(36);
while (sc.hasNextInt()) {
    list.add(sc.nextInt());
}
System.out.println(list);

Upvotes: 1

chiastic-security
chiastic-security

Reputation: 20520

You're incrementing spine as you put values into the array, so when you then print out temp[spine], you're printing the next one, which you haven't filled yet!

Change this

    while(sc.hasNextInt()){
            temp[spine++] = sc.nextInt();
            System.out.println("" + temp[spine]);
        }

to

    while(sc.hasNextInt()){
            temp[spine] = sc.nextInt();
            System.out.println("" + temp[spine]);
            spine++;
        }

Upvotes: 1

Related Questions