import java.util.Scanner; import java.io.File; import java.io.FileReader; import java.io.BufferedReader; public class Q4 { public static char[] readFile(String fileName) { String allCharacters; try { File file = new File(fileName); BufferedReader reader = new BufferedReader(new FileReader(file)); StringBuffer buffer = new StringBuffer(); String s; while ((s = reader.readLine()) != null) buffer.append(s.trim()); reader.close(); allCharacters = buffer.toString(); } catch (Exception ex) { return null; } return allCharacters.toCharArray(); } public static void sort(char[] sequence) { if (sequence == null) return; for (int i = 0; i < sequence.length - 1; i++) { int indexMin = i; for (int j = i + 1; j < sequence.length; j++) { if (sequence[j] < sequence[indexMin]) indexMin = j; } char temp = sequence[indexMin]; sequence[indexMin] = sequence[i]; sequence[i] = temp; } } public static String getPrintFormat(char[] sequence) { if (sequence == null) return "[]"; StringBuffer output = new StringBuffer(); output.append('['); for (int i = 0; i < sequence.length; i++) { output.append('\'').append(sequence[i]).append('\''); if (i < sequence.length - 1) output.append(',').append(' '); } output.append(']'); return output.toString(); } public static char[] cleanUp(char[] sequence) { if (sequence == null) return null; sort(sequence); StringBuffer result = new StringBuffer(); int i = 0; while (i < sequence.length - 1) { if (sequence[i] == '*' || sequence[i] != sequence[i + 1]) { i = i + 1; } else { result.append(sequence[i]).append(sequence[i + 1]); i = i + 2; } } return result.toString().toCharArray(); } public static boolean isRigorous(char[] sequence) { if (sequence == null) return true; sort(sequence); for (int i = 0; i < sequence.length - 2; i++) if (sequence[i] == sequence[i + 2]) return false; return true; } public static void main(String[] args) { String fileName; Scanner in = new Scanner(System.in); System.out.print("Please enter the name of the file to read: "); fileName = in.nextLine(); if (fileName.trim().isEmpty()) { System.out.println("No file name provided!"); return; } char[] fileInput = readFile(fileName); System.out.println(); System.out.println("Before cleanup: "); System.out.println(getPrintFormat(fileInput)); System.out.println(); System.out.println("After cleanup: "); char[] cleanedUpFile = cleanUp(fileInput); System.out.println(getPrintFormat(cleanedUpFile)); System.out.println(); if (isRigorous(cleanedUpFile)) System.out.println( "This list is now rigorous; it has no * and it has " + cleanedUpFile.length + " characters."); else System.out.println( "This list has no * but is not rigorous and it has " + cleanedUpFile.length + " characters."); } }