Luis Rojas
Luis Rojas

Reputation: 3

text file returning null and 0.0

I am trying to read a text file with 6 elements in it and put it into two arrays. The first element of the text I'm trying to read is a string and the second is a double. However when I call println to verify the output, it prints null and 0.0.

import java.io.*;
import java.util.*;

public class inputFile {

public static void main(String[] args) throws FileNotFoundException{

    String [] studNum = new String [25];
    double [] grade = new double [25];



    File findFile = new File ("//Users//luiserojas//Documents//holaFile.txt");
    Scanner inFile = new Scanner (findFile);

    int index = 0;

        while (inFile.hasNext()){
            studNum [index] = inFile.next();
            grade [index] = inFile.nextDouble();
            index ++;
            System.out.println(studNum[index] + grade[index]); 
        }

        }

}

Upvotes: 0

Views: 202

Answers (3)

Prabhaker A
Prabhaker A

Reputation: 8473

You are printing the values after the incrementing of index,So default values are dsiplaying.So first print and next increment index like this.

while (inFile.hasNext()){
            studNum [index] = inFile.next();
            grade [index] = inFile.nextDouble();
            System.out.println(studNum[index] + grade[index]); 
            index ++;
        }

Upvotes: 1

user1231232141214124
user1231232141214124

Reputation: 1349

You are incrementing index before you print the values, nothing is stored there yet. You need to put index++ after the println()

Upvotes: 1

Oleg Pyzhcov
Oleg Pyzhcov

Reputation: 7353

You're incrementing index before you print items so you try to print items that were not yet added, which have default-constructed values of null and 0.0d your arrays are filled with when they're created. Just reordering the following lines like this shall help:

        System.out.println(studNum[index] + grade[index]); 
        index ++;

Upvotes: 4

Related Questions