Reputation: 15
I've looked at other questions asked, and most use splitting and I'm not using that, nor have they been appropriately answered based on my situation. Practicing with Array, now trying to pull Strings from a file. Here is my Main Class
Scanner fileIn = null; // Initializes fileIn to an empty object
try
{
// Attempt to open the file
FileInputStream file = new FileInputStream("questions.dat");
fileIn = new Scanner(file);
}
catch (FileNotFoundException e)
{
// If the file could not be found, this code is executed
// and then the program exits
System.out.println("File not found.");
System.exit(0);
}
String line = "";
int i = 0;
String question[] = new String[5];
for(i=0; i < question.length; i++)
{
while(fileIn.hasNextLine())
{
line = fileIn.nextLine();
System.out.println(line);
question[i] = fileIn.nextLine();
}
System.out.println(Arrays.toString(question));
}
From some reason, when it prints question[] it prints [7, null, null, null, null]. I have no clue why. Is my Array not actually filled with the Strings? Example String. How many days in a week are there? seven. How many fingers do most people have? ten. This is the last string. Where is the Program getting null from?
Upvotes: 0
Views: 857
Reputation: 1873
also building up on @kOner answer, this will work better
for(i=0; i < question.length && fileIn.hasNextLine(); i++)
{
line = fileIn.nextLine();
System.out.println(line);
question[i] = line;
}
System.out.println(Arrays.toString(question));
Upvotes: 0
Reputation: 1116
You have nested loops and you fill only very first element in your array:
for(i=0; i < question.length; i++)
{
while(fileIn.hasNextLine())
{
line = fileIn.nextLine();
System.out.println(line);
question[i] = fileIn.nextLine();
}
System.out.println(Arrays.toString(question));
}
You need to remove the inner loop:
for(i=0; i < question.length; i++)
{
if(fileIn.hasNextLine())
{
line = fileIn.nextLine();
System.out.println(line);
question[i] = line;
}
System.out.println(Arrays.toString(question));
}
Upvotes: 4