使用数组设置高分

Setting up a highscore by using arrays

所以我们的老师告诉我们要创造一个JApplet的高分。

他希望我们使用包含 10 个整数值的 Arraylist。如果您按 JButton,这些值将显示在 JLabel 中。您可以输入一个数字及其在数组中的位置。就像我输入 10 并在另一个文本字段 0 中一样,数字 10 是我按下按钮时显示的第一个数字。但是其他 10 个整数值应该在数组中向上移动一位。

例如我什么都不输入我得到显示

1,2,3,4,5,6,7,8,9,10

当我输入 10 和 0 时,它应该显示

10,1,2,3,4,5,6,7,8,9,10. 

我的问题是我不知道如何移动数字,就像我只有输入 10 和 0 才能得到这个东西:

10,2,3,4,5,6,7,8,9,10

这是我的代码:

public void neueListe (int Stelle,int Zahl, int[] highscore){
    highscore[Stelle] = Zahl;
}

public void jButton1_ActionPerformed(ActionEvent evt) {
    int Stelle = Integer.parseInt(jTextField2.getText());
    int Zahl = Integer.parseInt(jTextField1.getText());
    int[] highscore = new int [10];
    highscore[0]=1;
    highscore[1]=2;
    highscore[2]=3;
    highscore[3]=4;
    highscore[4]=5;
    highscore[5]=6;
    highscore[6]=7;
    highscore[7]=8;
    highscore[8]=9;
    highscore[9]=10;

    neueListe(Stelle,Zahl, highscore);
    jLabel1.setText(""+ highscore[0]+", " + highscore[1]+", " + highscore[2]+", "+ highscore[3] + highscore[4] + highscore[5] + highscore[6] + highscore[7] + highscore[8] + highscore[9]);
}

将您的 int[] 转换为 ArrayList,然后使用 add 方法在任何位置简单地添加任何元素。

ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(highscore));

arr.add(Zahl, Stelle);  // arr.add(position, value) 
System.out.println(arr);

如果你想将所有 no.s 打印为字符串,那么使用这个。

String labelshow = "";
for(Integer item: arr){
   labelshow += "," + item;
}
jLabel1.setText(labelshow);

或者您可以简单地输入您的号码。在所需位置并使用 for loop 将其余元素向右移动。(请记住这一点,尺寸会增加。)

 int newarray[] = new int[highscore.length+1];
 for(int i=0, j=0; i<highscore.length+1; i++){
     if(i == Zahl){
          newarray[i] = Stelle;
     }
     else{
          newarray[i] = highscore[j++];
     }
 }

newarray 包含您的结果数组。您可以打印它或在 JLabel.

中显示它