Search code examples
javaarraysswingjapplet

Setting up a highscore by using arrays


So our teacher told us to create a JApplet with a highscore.

He wanted us to use an Arraylist which contains 10 integer values. If u press a JButton these values are getting displayed in a JLabel. And you can enter a number and where it is placed in the Array. Like if I enter 10 and in the other text field 0, the number 10 is the first number which gets displayed when I press the button. But the other 10 integer values are supposed to move one digit up in the array.

e.g I enter nothing I get displayed

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

and when I enter 10 and 0 it should display

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

My problem is that I don't get how to move the numbers like I can only get this thing if I enter 10 and 0:

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

Here is my Code:

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]);
}

Solution

  • Convert your int[] into ArrayList and then simply add any element at any position using add method.

    ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(highscore));
    
    arr.add(Zahl, Stelle);  // arr.add(position, value) 
    System.out.println(arr);
    

    if you want to print all no.s as string then use this.

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

    Or you can simply put your no. in required position and shift rest of the elements towards right using a for loop.(size would be increased keep this in mind.)

     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 contains your resultant array. You can print it or show it in JLabel.