-1

I need to make a program which reads a file in a method. The file is a "data.txt" type and will have a list of numbers (double data type) with one number on each line. Ex:

23.4
12.3
111.4533

I need to then put this in an array (NOT a 2D array)and return it to the main method. I used filename.length() but it makes the array size larger than it should be and I'm getting an array out of bounds error. I can initialize the array in a while loop, but it keeps saying I need to declare the size of the array first and I don't know how to do this. So I tried just using a while loop to get the number of lines and then using another loop to input the elements but it won't let me return the array to the main method without initializing the array. Here's what I have so far:

java.io.File file = new java.io.File(file);
int arraySize = (int)file.length();
int size = 0;
int i = 0;
try{
    Scanner input = new Scanner(file);
    while(input.hasNextLine()){
        size++;
    }    
    double [] array;
    array1 = new double [size];

    while(input.hasNext()){
        array[i] = input.nextDouble();
        i++;
    }

Any suggestions? I'm really stuck on this. Thanks.

  • 5
    Use an ArrayList instead of array, so that you don't need to know the size ahead of time. If you still need to return an array, convert the ArrayList to an array before you return. – musical_coder Apr 27 '14 at 18:07
  • I haven't used an array list before and I need to use a plain array unfortunately. – user3552956 Apr 28 '14 at 02:45

5 Answers5

1

Two possible solutions:

a) Use a collection which grows on demand instead of using a fixed array (e.g., ArrayList). You can also convert it afterwards into an array again.

b) Close the scanner and open the file again after you counted the number of lines.

nils
  • 1,362
  • 1
  • 8
  • 15
0

Assuming your filename variable is a String of the file's name then filename.length is only giving you the total characters in the name. If you have called your File object filename then filename.length() returns a long of the file's length in bytes and not the number of rows inside it.

To get the number of lines in a file you can refer to this question for many possible answers: Number of lines in a file in Java

But more likely you want to use an expandable Collection instead of a fixed length array as you do not then need to calculate and read the whole file before you begin using it. Something like an ArrayList could be ideal. But it does depend on your use case.
You can always convert the ArrayList back to an Array afterwards:

String[] lines = lineList.toArray(new String[lineList.size()]);
Community
  • 1
  • 1
indivisible
  • 4,892
  • 4
  • 31
  • 50
0

I would recommend using an ArrayList. That way you don't have to be aware of the size while creating the array. As other's have said, you can convert to a array after you are done adding values to the ArrayList.

Assuming your data.txt file has your doubles line by line with no spaces. you could use the following code:

    ArrayList <Double> doubleArray = new ArrayList<Double>();
    Scanner fileScan = null;

    try {
        fileScan = new Scanner(new File("/path/to/file"));
        while (fileScan.hasNextDouble()){
             doubleArray.add(fileScan.nextDouble());
    }

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }   
Bryan
  • 1,938
  • 13
  • 12
0

The problem right now is that you are not redefining the Scanner, so after you determine the size, the Scanner is at the end of the file and so there are no more doubles to be read in.

Also, when determining the size, you need to actually read in the line each loop so you skip to new lines, or else I think you will have an infinite loop. If you never read in a line, it always has more.

Try this (tested and works):

java.io.File file = new java.io.File(file);
int size = 0;
int i = 0;
try {
    Scanner input = new Scanner(file);
    while(input.hasNextLine()){
        input.nextLine(); // have to change the lines
        size++;
    }    
    double [] array;
    array = new double [size];

    // reopen the file so you start from the beginning again
    input = new Scanner(file);

    while(input.hasNext()){
        array[i] = input.nextDouble();
        i++;
    }

    // print out the array
    for (double d : array) {
        System.out.println(d);
    }

} catch (Exception e) {
    e.printStackTrace();
}

Or you could just use an ArrayList which has no defined size (you can .add elements to it and so you don't need to know the size beforehand to populate it). And then just convert the ArrayList to a regular array afterword if you wanted to.

Try this:

java.io.File file = new java.io.File("C:\\Users\\Mike\\Desktop\\data.txt");
try {
    Scanner input = new Scanner(file);
    ArrayList<Double> list = new ArrayList<Double>(); // define empty ArrayList

    while(input.hasNextLine()) {
        list.add(input.nextDouble()); // have to change the lines
    }

    // convert ArrayList to array
        // (although you don't need to do this if you're fine with an ArrayList)
    double[] array = new double[list.size()];
    for (int i = 0; i < list.size(); i++) {
        array[i] = list.get(i);
    }

    // print out the array
    for (double d : array) {
        System.out.println(d);
    }

} catch (Exception e) {
    e.printStackTrace();
}
Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97
  • Thank you SOO much! You helped a lot. It did work, but I had to change some things to keep the .hasNextLine() from running infinitely. – user3552956 Apr 28 '14 at 02:41
0

use below code

read line by line of text file and parse each line element to double add double parsed value to arraylist

convert arraylist to array.

String fileName=null;
     File file = null;
    try {
          fileName="path/filename.txt";
             file = new File(fileName);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        // TODO: handle exception
    }

List<Double> elements = new ArrayList<>();

    try{
        Scanner input = new Scanner(file);
      while(input.hasNextLine()){
          elements.add(Double.parseDouble(input.nextLine()));
      }

          double[] ret = new double[elements.size()];
          for(int index = 0;index < ret.length;index++)
            ret[index] = elements.get(index);

     System.out.println(ret);
     System.out.println("end");
}
    catch(Exception e){

    }
Karibasappa G C
  • 2,686
  • 1
  • 18
  • 27