AJJ
AJJ

Reputation: 897

Read and store integers in array

i am fairly new to java, i have some code which isn't quite working properly and i am not sure why so any help would be appreciated.

I am trying to read integers from a text file and store them in an array. Here is my code :

Scanner keyboard = new Scanner(System.in);

    File file = new File ("Grades.txt");
    FileReader input = new FileReader(file);
    BufferedReader in = new BufferedReader(input);

    int [] id = new int [500];

    String s = in.readLine();
    String s1 = s.substring(0,5);

    while (s != null){
        int i = 0;
        id[i] = Integer.parseInt(s1);
        System.out.println(id[i]);
        s = in.readLine();
    }
    in.close();

The problem i am having is that it only stores the first integer from the text file and displays the same integer for the following lines. Here is my output :

57363
57363
57363
57363
57363
57363
57363

Also here is the layout of the text file i am reading :

57363 Joy Ryder D D C P H H C D
72992 Laura Norder H H H D D H H H
71258 Eileen Over C F C D C C C P
70541 Ben Dover F F F P C C C F
46485 Justin Time F C F C D P D H
61391 Anna Conda D D F D D F D D
88985 Bob Down P F P F P F P P

Upvotes: 1

Views: 172

Answers (2)

aioobe
aioobe

Reputation: 420921

You're overwriting id[0] over and over again. You need to increment the index variable i in the loop. Also, s1 is never updated.

int i = 0;
while (s != null){
    id[i] = Integer.parseInt(s.substring(0, 5));
    System.out.println(id[i]);
    s = in.readLine();
    i++;    
}

A better way to solve this however is to use a Scanner:

Scanner s = new Scanner(new File("Grades.txt"));
int i = 0;
while (s.hasNextLine()) {
    id[i] = s.nextInt();
    System.out.println(id[i]);
    // (The remaining fields could be read with s.next())
    s.nextLine(); // skip rest of line
    i++;
}

Upvotes: 6

jBeenenga
jBeenenga

Reputation: 317

You never change s1 and never increment i:

String s = in.readLine();
String s1 = s.substring(0,5);

while (s != null){
    int i = 0;
    id[i] = Integer.parseInt(s1);
    System.out.println(id[i]);
    s = in.readLine();
}

I think this is what you wnat to do:

String s = in.readLine();
String s1 = s.substring(0,5);
int i = 0;
while (s != null){
    id[i] = Integer.parseInt(s1);
    System.out.println(id[i]);
    s = in.readLine();
    s1 = s.substring(0,5);
    i++
}

Upvotes: 1

Related Questions