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.