简体   繁体   中英

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

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++;
        }

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM