I'm trying to write a code that reads a Contacts list from a .txt file, sorts it by name and outputs it (sortByNames.txt) Then sorts it by their phone numbers and outputs a different new file (sortByNumbers.txt)
I.E:
Michael - 0001234567
Robert - 0019234568
Jacob - 0011234567
needs to become this by number:
Michael - 0001234567
Jacob - 0011234567
Robert - 0019234568
and this by name:
Jacob - 0011234567
Michael - 0001234567
Robert - 0019234568
Here's what I have so far:
public static void Save(String[][] vals, File f) throws Exception {
PrintWriter output = new PrintWriter(f);
for (int rows = 0; rows < vals.length; rows++) {
for (int cols = 0; cols < vals[rows].length; cols++) {
output.print(vals[rows][cols]);
output.print(" ");
}
output.println();
}
output.flush();
output.close();
return;
}
public static int CountLines(File f, Scanner reader) throws Exception {
int lines = 0;
while (reader.hasNextLine()) {
String s = reader.nextLine();
s = s.trim();
if (s.length() == 0) {
break;
}
lines++;
}
return lines;
}
public static void main(String[] args) throws Exception {
File contacts = new File("Contacts.txt");
Scanner reader = new Scanner(contacts);
String[][] s = new String[CountLines(contacts, reader)][2];
File name = new File("SortedByName.txt");
File number = new File("SortedByNumber.txt");
}
As you can see, I've figured out how many contacts there are and how to save the data into a .txt file.
HOWEVER, I can't figure out how to sort it by either their numbers or even their names.
Can someone please help me out with this? I've been racking my brain for the past couple hours and I've tried searching it up (But it leads me to code I can't understand).
How do I sort by Names? How do I sort by their numbers?
Thank you so much for any and all help!!