如何在没有Java.util.array的情况下在Java中的两个数组中查找位置
我有两个数组:名称[10]和点[10] “名称”包含玩家的姓名、点数及其点数 我想用参数字符串newName和int newPoints编写一个方法如何在没有Java.util.array的情况下在Java中的两个数组中查找位置,java,arrays,Java,Arrays,我有两个数组:名称[10]和点[10] “名称”包含玩家的姓名、点数及其点数 我想用参数字符串newName和int newPoints编写一个方法 根据点找到正确的位置(因此newPoints=500位于数组值之间) (300和600) 将点和名称的所有值在索引中向后移动1个位置-为 newPoints和newName 将newPoints和newName的值保存在空数组空间中 我不知道如何在数组点[]中找到正确的位置 以下是我在这一点上的做法: public void enterSor
public void enterSorted(String nameNew, int pointsNew) {
int indexPlace;
for(int i = points.length-1; i >= 0; i--) { //starts with i=10 (last array entry); stops when i is below 0
if(points[i] > pointsNew) {
indexPlace = i+1;
System.out.println("indexPlace "+indexPlace+" was saved. ");
break;
}
System.out.println("points[" + i + "] ("+points[i]+ "is smaller than pointsNew - proceeding");
}
}
请删除,不能删除
问题在答案发布后更改-ArrayIndexOutOfBoundsException
应该是SO中常见的问题
对于未来,更多OO:使用
列表
或甚至SortedMap
记录代替数组:public record Player(String name,int points){}
首先,由于您总是在数组中寻找正确的位置,因此我们可以假设,我们的两个数组是按递增点排序的,因此我们不需要对数组进行任何排序,只需要插入。
为此,我们搜索第一个位置,该位置的点数高于我们所拥有的点数(我用max int初始化了all,否则在未使用的字段中有零)。然后我们可以将那些从那个位置向后移动到最后定义的位置(我决定为第一个未定义的字段定义一个索引,但是您只能检查maxInt,尽管使用这个变量我们可以检查数组是否已满),最后写入数据。
如果pos==firstUndef,我们就在所有已经定义的后面,不需要移动任何东西
public class Tested {
public String[] names = new String[10];
public int[] points = new int[10];
public int firstUndef = 0;
public void initPoints() {
for (int i = 0; i < points.length; i++) {
points[i] = Integer.MAX_VALUE;
}
}
public void addPlayer(String name, int point) {
assert(firstUndef < points.length); // if false there is no room left in the arrays
for (int i = 0; i <= firstUndef; i++) { // We only need to check for those defined and one more
if (points[i] > point) {
insertAt(name, point, i);
break;
}
}
}
public void insertAt(String name, int point, int pos) {
if (pos < firstUndef) {
for (int i = (firstUndef - 1); i >= pos; i--) {
points[i + 1] = points[i];
names[i + 1] = names[i];
}
}
points[pos] = point;
names[pos] = name;
firstUndef++;
}
}
顺便说一句:不要将变量设置为公共变量,我这样做只是为了快速测试它。到目前为止,您尝试了什么?你能分享你的努力吗?某种类型的树可能更适合这个用例?也许是二进制搜索tree@maloomeister我试图用包含if语句的for循环将这些值与points数组中的每个值进行比较。我只是觉得一定有更简单的方法solution@JudgeVFX分享你尝试过的代码,并指出你被卡住的地方。为什么不使用地图呢?哇,谢谢你的努力!我一定会尝试实现这种方法。重要的是在开始时使用initPoints,否则不会插入任何内容,否则它应该可以正常工作。在看了另一个答案后,我也换了一行,他只检查定义的位置。
Tested t = new Tested();
t.initPoints();
t.addPlayer("Peter", 300);
t.addPlayer("Frank", 600);
t.addPlayer("Avid", 500);
assert(t.names[0].equals("Peter"));
assert(t.names[1].equals("Avid"));
assert(t.names[2].equals("Frank"));