I have a textfile with some values.
textfile data
line1row1 line1row2 55
line2row1 line2row2 44
line3row1 line3row2 33
I have a data class where i have created a contructor. the data which goes into the array, i want read from the text file.
import java.io.*;
import java.util.*;
class Data{
public Data(String entry1, String entry2, int entry3){}
}
public class readData {
public static void main(String[] args) throws Exception{
BufferedReader inFile = new BufferedReader (new FileReader ("scores.txt"));
Data entrydata[] = new Data[3]; //create new constructor array
for(int i = 0; i < entrydata.length; i++ ){
entrydata[i] = inFile.readLine();
}
}
}
I get an error on “inFile.readLine()”… Cannot Convert from String to Data(where “Data” refers to class)
I can hardcode the data [as below] but want it to be read from the file instead
Data entrydata[] = new Data[3];
entrydata [0] = new Data("line1row1 ", "line1row2 ", 55);
entrydata [1] = new Data("line2row1 ", "line2row2 ", 44);
entrydata [2] = new Data("line3row1 ", "line3row2 ", 33);
The reason I want to do this, is so that I can access the informatin stored in the array.
inFile.readline() returns a string, which isn’t a Data object and so you get the error message. You need to split the string you read from the file into an array and the use the array elements to create your data items. Something like: