I am scanning a file that has an athelete's name and his scores:
John Smith; 24; 14;
Adam West; 17; 9;
How can I separate these values? As in John Smith is the name, 24 is his A score, 14 is his B score? I'm thinking to create an "Athlete" object with such parameters, but I don't know how to 'assign' them.
My scan:
File file = new File ("input.txt");
Scanner scan = new Scanner(file);
while(scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
CodePudding user response:
Based on how question was asked I assume that you start with Java (or programming).
Beginner approach would be to split each line:
String line = scan.nextLine();
String[] fields = line.split(";");
String name = fields[0];
String aScore = fields[1];
String bScore = fields[2];
Then you can figure out the rest. Of course this code needs error handling, because there can be less (or even no semicolons).
More on split: https://www.baeldung.com/string/split
In comercial environment instead of doing that on your own you'd be better off using one of available libraries that parse CSV-like files like Apache Commons CSV. Then you can define named headers and rely on external library to handle errors in input file for you.