gpt4 book ai didi

java - 如何跳过已访问(重复)值的索引?

转载 作者:行者123 更新时间:2023-12-02 05:45:19 25 4
gpt4 key购买 nike

所以基本上我需要创建一个包含学习时间的数组。第一个任务是获取总数并将它们存储在我完成的数组中,

 //student number        total hours
Student Weekly study
Student0 34
Student1 28
Student2 20
Student3 31
Student4 32
Student5 28
Student6 37
Student7 41

第二个任务是按照最长的时间来安排学生。我先把实际学习的时间排列在一个数组中:

public static void sort(Integer[] array){
Integer studentNumber [] = new Integer[8];
Integer temp[] = new Integer[8];
for (int i = 0; i < array.length;i++){
temp[i] = array[i];//declaring value of index so it doesn't change
}
Arrays.sort(array, Collections.reverseOrder());//sorted the original array in descending order
}

然后我需要显示学生(通过他们的原始索引号来识别他们,例如student0有34),所以我做了一个循环来比较两个值,如果是的话,那么它将使用“temp”的索引:

     for (int i = 0; i < temp.length;i++){
for (int j = 0; j < array.length;j++){
if (array[i].equals(temp[j] )){

System.out.println("Student" + j + "\t " + array[i]);
break;
}
}

输出:

     Student7    41
Student6 37
Student0 34
Student4 32
Student3 31
Student1 28
Student1 28
Student2 20

正如你所看到的,当它应该显示应该显示 5 时,它显示了 Student1 两次,但是因为它们具有相同的值,所以它会查找第一个与其相等的东西。

我正在寻找解决方案,我试图创建一个变量来检查索引是否已被访问:

    int pointer =0;
for (int i = 0; i < temp.length;i++){
for (int j = 0; j < array.length;j++){
if (array[i].equals(temp[j] )&& i > pointer){

System.out.println("Student" + j + "\t " + array[i]);
break;
}
}
pointer++;
}

所以我的问题是,有没有办法检查/跳过具有已访问过的重复值的索引

最佳答案

Java 有一些内置的工具,使用它们比为简单的事情编写自己的算法更容易。

使用LinkedHashMap将数据存储为键值对。然后迭代映射,并通过使用Comparator比较值将它们插入到另一个映射中。

LinkedHashMap<String, Integer> students = new LinkedHashMap<>(),
sortedStudents = new LinkedHashMap<>();

students.put("Student0", 34);
students.put("Student1", 28);
students.put("Student2", 20);
students.put("Student3", 31);
students.put("Student4", 32);
students.put("Student5", 28);
students.put("Student6", 37);
students.put("Student7", 41);

List<Map.Entry<String, Integer>> list = new ArrayList<>(students.entrySet());
list.sort(Entry.comparingByValue(new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
if (o1.intValue() < o2.intValue()) {
return 1;
} else if (o1.intValue() > o2.intValue()) {
return -1;
}
return 0;
}
}));

for (Entry<String, Integer> entry : list) {
sortedStudents.put(entry.getKey(), entry.getValue());
}

System.out.println(sortedStudents);

输出:

{Student7=41, Student6=37, Student0=34, Student4=32, Student3=31, Student1=28, Student5=28, Student2=20}

关于java - 如何跳过已访问(重复)值的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56100731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com