Today, another friend in the group asked me about this exercise. I simply paste the code here. Next time I need a friend, I can come and see it.
Knowledge points used: array, set, IO stream
Problem description: Read data to the memory in a txt file, as shown in. Then, count the number of each number in the column except 0 (put in Map) and sort the data by column size.
Code:
package com.test;import java.io.BufferedReader;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.Comparator;import java.util.List;import java.util.TreeMap;public class Week {private static List
readFile1(String fileName) {List
list = new ArrayList
();String line = "";int[] arr;FileReader fr = null;BufferedReader br = null;try {File file = new File(fileName);fr = new FileReader(file);br = new BufferedReader(fr);while (br.ready()) {line = br.readLine();String[] data = line.split(",");arr = new int[data.length];for (int j = 0; j < data.length; j++) {arr[j] = Integer.parseInt(data[j]);}list.add(arr);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally{if(br != null){try {br.close();} catch (IOException e) {e.printStackTrace();}}if(fr != null){try {fr.close();} catch (IOException e) {e.printStackTrace();}}}return list;}private static int[][] revertData(List
data) {int maxCol = 0;for (int i = 0; i < data.size(); i++) {if (data.get(i).length > maxCol) {maxCol = data.get(i).length;}}int[][] arrs = new int[maxCol][data.size()];for (int i = 0; i < data.size(); i++) {int[] arr = data.get(i);for (int j = 0; j < arr.length; j++) {arrs[j][i] = arr[j];}}return arrs;}private static void countKeyNum(int[][] arrs) {TreeMap
map;for (int i = 0; i < arrs.length; i++) {map = new TreeMap
(new Comparator
() {@Overridepublic int compare(Integer o1, Integer o2) {return o1.compareTo(o2);}});for (int j = 0; j < arrs[i].length; j++) {if (arrs[i][j] == 0)continue;if (map.containsKey(arrs[i][j])) {map.put(arrs[i][j], map.get(arrs[i][j]) + 1);} else {map.put(arrs[i][j], 1);}}System.out.println(map);}}public static void main(String args[]) {List
data = readFile1("week.txt");int[][] arrs = revertData(data);countKeyNum(arrs);}}
Some running results: