Question

I am inputting a file into my program that has over 4000 lines in it.

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class NameApp{

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

    readNamesFile(nameArray);

    for (int i = 0; i < 4429; i++){
        System.out.println(nameArray[i]);
    }

}

private static void readNamesFile(String[] nameArray) throws FileNotFoundException{
    Scanner inputStream = null;
    String fileName = "names.txt";
    inputStream = new Scanner (new File(fileName));

    int i = 0;

    while (inputStream.hasNextLine()){
        nameArray[i] = inputStream.nextLine();

        i++;
    }

    inputStream.close();
}

}

now the way that it is isn't working because my nameArray hasn't been initialized yet. Is there a way I can use the length of the text file I am inputting in to have my array that size? Or is it just best to find out the maximum total of inputs I will have (this <-- is my file by the way). 4429 is the amount of inputs in the file.. Just don't think I am able to use that number I did ask my professor though

Was it helpful?

Solution

You can use the LineNumberReader.

LineNumberReader  lnr = new LineNumberReader(new FileReader(new File("names.txt"))); // Your file name
lnr.skip(Long.MAX_VALUE);
int size = lnr.getLineNumber() + 1; // +1 because line numbering begins at 0
lnr.close();

// Use the size for your array declarationg
String[] nameArray = new String[size];

Note: To know the size, the file has to be read twice(if the you insist on using an array), either by manually looping through it or letting built-in classes do that. Otherwise, the you can use an ArrayList instead of an array, since an ArrayList is dynamic and thus, you don't have to worry about fixing a size.

OTHER TIPS

Your method signature is not correct. You should return String[]. Try,

 static String[] readNamesFile() {
    String[] nameArray= new  String[4429];
    //put the file String here
    ...........

   return  nameArray;
 }

At main method, get the return array and print

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

  String[] nameArray= readNamesFile();

 for (int i = 0; i < 4429; i++){
    System.out.println(nameArray[i]);
 }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top