Declare the second dimension of a stepped array

0

I have to do a stepped array, but I do not know how to do it so that at the time of asking the columns of the array are declared within the loop, the program should do this as many times as players put it.

Exit of the program

Enter the number of players: 3

Enter the number of games played by the player 1: 2
Enter the points of the match 1: 11
Enter match points 2: 15

Enter the number of games played by player 2: 3
Enter the points of the match 1: 8
Enter the points of the match 2: 5
Enter match points 3: 15

Enter the number of games played by player 3: 2
Enter the points of the match 1: 21
Enter match points 2: 18

I tried to do this, but only the last player fills me:

    //Variables
    System.out.print("Entra el número de jugadores: ");
    int numjuga = Integer.parseInt(teclat.readLine());
    int array[][] = new int[numjuga][];
    int numparti = 0;

    //Bucle para pedir partidos y puntuacion
    for ( int i=0; i<array.length; i++ ) {

        System.out.printf("Entra el número de partidos jugados por el jugado %d: ", i+1);
        numparti = Integer.parseInt(teclat.readLine());
        array = new int[numjuga][numparti];

        for ( int k=0; k<array[0].length; k++ ) { 
            System.out.printf("Entra los puntos del partido %d: ",k+1);
            array[i][k] = Integer.parseInt(teclat.readLine());
        }
    }
    
asked by Pol 16.12.2018 в 13:02
source

2 answers

1

What happens is that when you run array = new int[numjuga][numparti]; you are starting the array again, then all the data is lost.

Try putting the code like this:

array[i] = new int[numparti];
    
answered by 16.12.2018 / 21:30
source
0

When you reach array = new int[numjuga][numparti]; , as FrEqDe said, you are loading the existing list with a new one. Your answer should be worth it. I offer you an alternative because I am not a supporter of fixed lists

I would choose to change int array[][] by hashMap<Integer,ArrayList<Integer>> since you would forget about fixed sizes.

//Variables
System.out.print("Entra el número de jugadores: ");
int numjuga = Integer.parseInt(teclat.readLine());
Map<Integer, ArrayList<Integer>> array = HashMap<Integer, ArrayList<Integer>>();
int numparti = 0;

//Bucle para pedir partidos y puntuacion
for ( int i=0; i<array.length; i++ ) {

    System.out.printf("Entra el número de partidos jugados por el jugado %d: ", i+1);
    numparti = Integer.parseInt(teclat.readLine());
    List<Integer> lista = new ArrayList();
    array.put(numjuga, lista);

    for ( int k=0; k<numparti; k++ ) { 
        System.out.printf("Entra los puntos del partido %d: ",k+1);
        lista.add(Integer.parseInt(teclat.readLine()));
    }
}

(you may have some missing error (or a, since you did not have an IDE on hand to verify it 100%)

    
answered by 17.12.2018 в 10:21