In Java, this is a homework problem from my textbook that I\'m trying to underst
ID: 3907426 • Letter: I
Question
In Java, this is a homework problem from my textbook that I'm trying to understand, without the use of a String buffer, just a regular search and sort using Collections, an array list and comparator
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.Explanation / Answer
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 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); } } 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; // find index of first non-digit character starting from the end of the first string for(int i = s1.length()-1; i >= 0; --i) { if(!Character.isDigit(s1.charAt(i))) { index = i+1; break; } } // separate number and string n1 = Integer.parseInt(s1.substring(index)); w1 = s1.substring(0, index); index = 0; // find index of first non-digit character starting from the end of the second string for(int i = s2.length()-1; i >= 0; --i) { if(!Character.isDigit(s2.charAt(i))) { index = i+1; break; } } // separate number and string n2 = Integer.parseInt(s2.substring(index)); w2 = s2.substring(0, index); // compare the strings and numbers here and return comparision result int cmp = w1.compareTo(w2); if(cmp == 0) { return Integer.compare(n1, n2); } else { return cmp; } } }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.