0

How do I read in a file into a string array using Scanner? The file has a specified number of lines, lets say 100. There are plenty of examples in here using arrayList and BufferedReader but not Scanner or arrays that are already fixed in size.

public String[] array;
Scanner inputStream = null;     
public String line;

public practice(String theFile) {      
    array = new String[100];
    try {         
        inputStream = new Scanner(new FileInputStream(theFile)); 

        while (inputStream.hasNextLine()) {
            for (int i = 0; i < array.length; i++){

                //dont know what to put here         
             }
         }           
     } catch(FileNotFoundException e) {
         System.out.println(e.getMessage());
     }
     inputStream.close();   
}
1
  • You don't need to check for has next line because you have a fixed length and a try catch to handle it all. Just use the for loop but not the while loop. Commented Mar 25, 2015 at 0:43

2 Answers 2

2

You don't need to check for has next line because you have a fixed length and a try catch to handle it all. Just use the for loop but not the while loop. From there, it's just all scanner stuff:

for (int i = 0; i < array.length; i++)
{
    array[i] = inputStream.nextLine();        
}
Sign up to request clarification or add additional context in comments.

1 Comment

I see, once I took of my while loop it worked. Thank you very much! Once I reach 15 rep points I make sure to upvote your answer. Thanks again!
1
int i = 0;

while (inputStream.hasNextLine() && i < array.length())
{
    array[i] = inputStream.nextLine(); 
    i++;
}    

2 Comments

not a problem :) i must say: using a try..catch block as a pettern of not handling common exceptions (such as out of range) is a very bad practice. please use try.. catch ONLY when the effort of trying to map all the posibble exceptions and their solutions is not possible or the resulted code will probably will be too messy
Hm, but the reason I used a try and catch was because I kept getting compile errors which were due to exceptions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.