我的程序模拟电梯的操作,每次“用户”使用电梯时,它都会在文本文件中创建一行。
文本文件示例:
25/03/14_05:09:24 Slccj Azeepc 1 2
25/03/14_05:37:48 Wfvp Dvjhlwvpc 3 5
25/03/14_05:38:27 Mfkk Wtrsejplc 2 1
25/03/14_05:39:00 Qczoz Mlrrtyd 0 4
每次使用都会在文件中创建一行,其中包含时间戳、(编码的)用户名、进入电梯的楼层以及下车的楼层。
我一直在尝试弄清楚如何打印一份报告,该报告按降序详细说明每个用户使用电梯的次数。
这是我到目前为止所拥有的:
public void showUseCount2() {
int[] userCount = new int[4];
String[] users = new String[4];
users[0] = "Wfvp Dvjhlwvpc";
users[1] = "Qczoz Mlrrtyd";
users[2] = "Slccj Azeepc";
users[3] = "Mfkk Wtrsejplc";
try {
String strLine;
for (int i = 0; i < userCount.length; i++) {
FileInputStream fis = new FileInputStream("reports.txt");
DataInputStream dis = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(dis));
while ((strLine = br.readLine()) != null) {
int startIndex = strLine.indexOf(users[i]);
while (startIndex != -1) {
userCount[i]++;
startIndex = strLine.indexOf(users[i], startIndex + users[i].length());
}
}
dis.close();
}
Arrays.sort(userCount);
System.out.println(Arrays.asList(userCount));
}
catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
System.out.println("Wfvp Dvjhlwvpc used the lift: " + userCount[0] + " times");
System.out.println("Qczoz Mlrrtyd used the lift: " + userCount[1] + " times");
System.out.println("Slccj Azeepc used the lift: " + userCount[2] + " times");
System.out.println("Mfkk Wtrsejplc used the lift: " + userCount[3] + " times");
}
这是我目前得到的输出:
[[I@19b04e2]
Wfvp Dvjhlwvpc used the lift: 1 times
Qczoz Mlrrtyd used the lift: 1 times
Slccj Azeepc used the lift: 1 times
Mfkk Wtrsejplc used the lift: 2 times
所以我的for
循环成功填充userCount
大批。我尝试过使用 Arrays.sort
但它似乎不适合我。因此,我需要一种方法来对数组中的这些数字进行排序,同时维护用户及其使用计数之间的关系。任何帮助将不胜感激!
最佳答案
您需要定义一个类来保存您要排序的值以及您想要关联的其他信息,而不是对 int
数组进行排序它。然后,您将对这些对象的数组进行排序,而不是对 int
数组进行排序。您可以使该类实现Comparable
,也可以定义一个Comparator
,将其作为第二个参数传递给Arrays.sort
。示例:
class User implements Comparable<User> {
private int count;
public User (String name) {
this.name = name;
count = 0;
}
public void incrementCount() {
count++;
}
@Override
public int compareTo(User other) {
return Integer.compare(count, other.count);
// Or if you want compareTo to return the reverse result, so that you can sort
// in descending order:
// return Integer.compare(other.count, count);
}
}
关于java - 对整数数组进行排序,同时保持与字符串数组的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22645321/