I'm writing a program in Java that reads data from a text file into an Arraylist. The text file has 10 lines of data and each line contains a piece of data in the format of: "Integer1-String1:String2" example: "123-ABC:DEFG".I would like to save Integer1, String1 and String2 like this:
int listNumber; //This would be Integer1
String listData1; //This would be String1
String listData2; //This would be String2
So my question is how can I do this without saving each type of data into separate array. I was thinking about something like this but it's not working:
int givenNumber = Integer.parseInt(myArrayList.substring(0, "-"));
Here is what I have so far:
final String INPUT = "data.txt";
Scanner input = new Scanner(new FileReader(INPUT));
ArrayList<String> myArrayList = new ArrayList<String>();
while (input.hasNext()){
myArrayList.add(input.next());
}
for (int i = 0; i < myArrayList.size(); i++) {
int givenNumber = Integer.parseInt(myArrayList.substring(0, "-"));
System.out.println(myArrayList.get(i)); //Print the all data
}
Sorry if this information is not clear but I'm new to Java and and don't know to describe it better.
You might want to create a helper class for your data:
class ListData {
int listNumber;
String listData1;
String listData2;
ListData(int listNumber, String listData1, String listData2) {
this.listNumber = listNumber;
this.listData1 = listData1;
this.listData2 = listData2;
}
@Override
public String toString(){
return listNumber + "-" + listData1 + ":" + listData2;
}
}
And then store it in a Array of ListData:
List<ListData> datalist = new ArrayList<>();
datalist.add(new ListData(listNumber, listData1, listData2);
EDIT:
Your implementation is not parsing the data from the scanner. The following snippet parses the Scanner
input line by line adding to the list.
while (input.hasNext()) {
// Read each line from the scanner
String input = input.next();
// Split data on two delimiters '-' and ':'
String[] data = input.split("-|:");
int listNumber = Integer.parseInt(data[0]);
String listData1 = data[1];
String listData2 = data[2];
// Add to the datalist
datalist.add(new ListData(listNumber, listData1, listData2));
}