I have this text file containing various information so far I've been able to read everything except the Address details as they're separated by spaces and contain both numbers and letters so I'm a bit stuck as to what to do I've tried reading it as an int but I know that it wouldn't work.
This is my code:
public void methodName() {
File vData = new File("src/volunteer_data.txt"); // Create file object
try { // try catch to handle exception
Scanner readFile = new Scanner(vData); // Create scanner object
while (readFile.hasNextLine()) { //
int volunteerID = readFile.nextInt(); // Read volunteerID as an int
String vName = readFile.nextLine(); // Read volunteer name as string
// DATATYPE address = readFile.nextSOMETHING(); // Read address as ....
String contact = readFile.nextLine(); // Read contact number as a string
}
readFile.close(); // Close scanner
} catch(FileNotFoundException e) { // Throw exception and stop program if error found
e.printStackTrace();
}
Here is the text file that I am reading from. It is tab delimited:
VolunteerID Name Address Contact
050 John 24 Willow Street 905-747-0876
042 Emily 362 Sunset Avenue 905-323-1234
013 Alice 16 Wonderland Street 905-678-0987
071 Arthur 36 York Road 905-242-5643
060 Daniel 125 Ottawa Street 905-666-3290
055 Peppa 64 Great Britain Blvd 905-212-4365
024 Sean 909 Green Avenue 905-232-5445
077 Kim 678 Grape Garden 905-080-7641
098 Patrick 126 Oxford Street 905-099-9535
092 Laura 45 Mill Street 905-244-0086
008 Gary 84 California Street 905-767-3456
CodePudding user response:
My advice is to forget scanning each column separately using nextInt()
etc. It leads to pain and suffering in the long run. Instead, scan the whole line and work with the line: split it into a String[]
of columns, then work with the columns separately:
readFile.nextLine(); // skip heading line (if there is one)
while (readFile.hasNextLine()) {
String line = readFile.nextLine(); // read whole line
String[] columns = line.split("\t"); // split line on tab char
// get each column into variables
int volunteerID = Integer.parseInt(columns[0]);
String vName = columns[1];
String address = columns[2]; // no big deal
String contact = columns[3];
// do something with variables
}
Strictly speaking, you don't even need the variables. Yo could work directly with the array and an index, but it's much easier to read and debug when you use well-named variables.