我在一个单独的 .java 文件中使用 ArrayList 类方法等,因为我继续致力于高分功能。现在,安排两个相等的分数符合我的目的,使得分数 n 的第一个实例(如果它是第一个分数,则在它之前不等于)在列表中保持高于分数 n 的第二个实例。我已经使用了两种排序方法,但它总是跳过我尝试使用 == 比较的循环的任何部分。我正在手动设置值“测试”(参见代码)。代码如下,如果有任何似乎难以理解的地方,请随时提及。调试的东西被注释掉了。
import java.util.*;
public class arraylisttest
{
public static void main(String[] args)
{
ArrayList<Integer> grn = new ArrayList<Integer>();
System.out.println("Empty:");
for (int i = 0; i < grn.size(); i++)
{
System.out.println("Key" + i + " : " + grn.get(i));
}
grn.add(122);
grn.add(534);
grn.add(132);
grn.add(310);
grn.add(267);
grn.add(322);
System.out.println("Full:");
for (int i = 0; i < grn.size(); i++)
{
System.out.println("Key" + i + " : " + grn.get(i));
}
int myscore = 534;
Integer test = myscore;//reassignment, not entirely necessary
int y = 0;
Collections.sort(grn);
System.out.println("Sorted: ");
for (int i = 0; i < grn.size(); i++)
{
System.out.println("Key" + i + " : " + grn.get(i));
}
//fix sort so that number is added correctly if equal to last element
int max = grn.size();
if(test > grn.get(y))
{
if(test < grn.get(max - 1))
{
System.out.println("bigger, sm max");
grn.set(y, test);//in at 0
y++;//now 1
while (grn.get(y) < test)
{
grn.set(y-1, grn.get(y));//shift this one down
grn.set(y, test);//fill the hole
y++;//ends up at 5
}
}
else if(test > grn.get(max-1))
{
System.out.println("bigger, gr max");
int temp = grn.get(max-1);
grn.set(max-1, test);//in at end
y++;
while(y < (max-1))
{
grn.set(y-1, grn.get(y));//shift this one down
grn.set(y, grn.get(y+1));//fill the hole
y++;//ends up at 5
}
grn.set(max-2, temp);
}
else if(test == grn.get(max-1))//error here
{
System.out.println("bigger, eq max");
y++;//now 1
while (grn.get(y) < test)
{
grn.set(y-1, grn.get(y));
grn.set(y, test);
y++;
}
grn.set(y-1, test);
}
else
{
System.out.println("Oops.");
}
}
else
{
System.out.println("too small");
}
//end sort
//System.out.println("Test: " + test);
//System.out.println("Myscore: " +myscore);
System.out.println("Sort" + y + " : ");
for (int i = 0; i < grn.size(); i++)
{
System.out.println("Key" + i + " : " + grn.get(i));
}
请注意,据我所知,前两种按预期工作。