It is common for people to name directories as dir1, dir2, and so on. When there
ID: 3906406 • Letter: I
Question
It is common for people to name directories as dir1, dir2, and so on. When there are ten or more directories, the operating system displays them in dictionary order, as dir1, dir10, dir11, dir12, dir2, dir3, and so on. That is irritating, and it is easy to fix. Provide a comparator that compares strings that end in digit sequences in a way that makes sense to a human. First compare the part before the digit as strings, and then compare the numeric values of the digits.
Your program should work with the provided test program Call the class you write DirectoryComparator.java.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class DirectorySortDemo
{
public static void main(String[] args)
{
String[] dirNames = {"dir12", "dir5", "dir9", "dir1", "dir4",
"lab10", "lab2", "lab7", "lab17", "lab8",
"quiz8", "quiz10", "quiz11", "quiz12",
"dir11", "dir8", "dir7", "dir15", "dir3"};
ArrayList<String> directories = new ArrayList<>(Arrays.asList(dirNames));
System.out.println("Unsorted List:");
System.out.println(directories);
Collections.sort(directories, new DirectoryComparator());
System.out.println();
System.out.println("Sorted List:");
System.out.println(directories);
}
}
Explanation / Answer
import java.util.Comparator; public class DirectoryComparator implements Comparator { @Override public int compare(String s1, String s2) { String w1, w2; int n1, n2; int index = 0; for(int i = s1.length()-1; i >= 0; --i) { if(!Character.isDigit(s1.charAt(i))) { index = i+1; break; } } n1 = Integer.parseInt(s1.substring(index)); w1 = s1.substring(0, index); index = 0; for(int i = s2.length()-1; i >= 0; --i) { if(!Character.isDigit(s2.charAt(i))) { index = i+1; break; } } n2 = Integer.parseInt(s2.substring(index)); w2 = s2.substring(0, index); int cmp = w1.compareTo(w2); if(cmp == 0) { return Integer.compare(n1, n2); } else { return cmp; } } }Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.