matrix series limit 4

1

My matrix currently prints:

  

1234

     

1234

     

1234

     

1234

I need to print only as follows:

  

1

     

12

     

123

     

1234

My code is this:

 Scanner pedir = new Scanner(System.in);
    int columnas;
    int filas;
    int i;
    int j;
    System.out.println("Escribe el numero de Columnas");
    columnas =pedir.nextInt();

    System.out.println("Escribe el numero de Columnas");
    filas =pedir.nextInt();
    int numPrimos[][] = new int [columnas][filas];

    for(i = 0;i<numPrimos.length;i++){
        int A ;
        for(j = 0;j <numPrimos.length;j++){
            numPrimos[i][j]=j;
            A = numPrimos[i][j];
        } 

    }

    for(i = 0;i<numPrimos.length;i++){
        for(j = 0;j <numPrimos.length;j++){
            System.out.print(numPrimos[i][j]);
        }System.out.print("\n");
    }

}

}

    
asked by Dïëgö Böhörqüëz 05.03.2018 в 14:42
source

3 answers

1

You have a problem in the loop you are using, to correctly do what you are looking for, you should have it this way:

public static void main(String[] args) {

    Scanner pedir = new Scanner(System.in);
    int num;
    string str = "";        

    //Sólo precisas de una pregunta de número.
    System.out.println("Escribe el numero de Columnas y Filas");
    num = pedir.nextInt();

    for(int i = 0; i <= num; i++) //Recorremos las filas
    {
        str = ""; //Reseteamos la variable para no guardar el numero anterior
        for(j = 1; j <= i; j++) //Recorremos las columnas dependiendo del numero de fila donde estemos
        {
            str = str + j; //Construimos el numero para imprimirlo
        } 
        System.out.print(str + "\n"); //Sacamos el numero por pantalla
    }
}

With this code you get the expected result.

If we put the number 4 you will get:

  

1

     

12

     

123

     

1234

    
answered by 05.03.2018 в 16:46
1

I understand that what is sought is to print as many characters as rows have been printed. To achieve this I would do so by modifying the limits of the loops in the following way:

    int columnas;
    int filas;
    int i;
    int j;
    //System.out.println("Escribe el numero de Columnas");
    //columnas =pedir.nextInt();
    //System.out.println("Escribe el numero de Columnas");
    //filas =pedir.nextInt();
    
    System.out.println("4 Columnas y 4 filas");
    columnas = filas = 4;
    int numPrimos[][] = new int [columnas][filas];
    
    for(i = 0;i<numPrimos.length;i++){
        //int A ; <- Linea innecesaria
        //for(j = 0;j <numPrimos.length;j++){
        for(j = 0;(j <= i && j<numPrimos[i].length);j++){ // De esta forma rellenamos los elementos que nos interesan únicamente. Esto es opcional pero según mi opinión si no se va a trabajar con un objeto mejor no instanciarlo para optimizar el proceso.
            numPrimos[i][j]=j+1; // Se añade 1 para que lo que se muestre en pantalla empieze en 1 y no en 0.
            //A = numPrimos[i][j]; <- Linea innecesaria
        } 

    }

    for(i = 0;i<numPrimos.length;i++){
        // Esta es la línea de código que cambiaría para conseguir dicho resultado
        //for(j = 0;j <numPrimos.length;j++){
        for(j = 0;(j <= i && j<numPrimos[i].length);j++){ // Así conseguimos que se impriman solo los carácteres que necesitamos sin llegar al limite numPrimos[i].length
            System.out.print(numPrimos[i][j]);
        }System.out.print("\n");
    }

I tell you about the changes. First the first loop has been changed, so that it only stores in the matrix the values with which it is going to work in this process. Before, the matrix was as follows:

[0][0] = 1    [1][0] = 1    [2][0] = 1    [3][0] = 1
[0][1] = 2    [1][1] = 2    [2][1] = 2    [3][1] = 2
[0][2] = 3    [1][2] = 3    [2][2] = 3    [3][2] = 3
[0][3] = 4    [1][3] = 4    [2][3] = 4    [3][3] = 4

After the change in the first loop, the matrix remains as follows:

[0][0] = 1    [1][0] = 1    [2][0] = 1    [3][0] = 1
[0][1] unde.  [1][1] = 2    [2][1] = 2    [3][1] = 2
[0][2] unde.  [1][2] unde.  [2][2] = 3    [3][2] = 3
[0][3] unde.  [1][3] unde.  [2][3] unde.  [3][3] = 4

On the other hand, the change in the second loop prevents that there are more laps than necessary when it comes to show. As you may have noticed, it is the same solution in both loops, to prevent it from turning more than you really need. In an example of 4 lines there is hardly any difference, but if the same code executes millions of records, the difference between doing it efficiently or not is much greater.

So that you can do the test, I add the results of having done it with the performance improvement and without it for a 400x400 matrix.

Sin mejora - 834ms.
Con mejora - 276ms.

I hope it helps you to take into account all the details when you look for a solution, a greeting.

    
answered by 05.03.2018 в 16:37
-2

Now that I have understood your question, I see that it is something that you could easily have done with the Debugging of your IDE to know what value has i and j to stop or follow the saving of values in a certain position. With the use of if I have achieved it quickly. I have commented the lines so that you can understand it.

Code:

import java.util.Scanner;

import javax.swing.JOptionPane;

public class Menu_1 {
    public static void main(String[] args) {

        Scanner pedir = new Scanner(System.in);
        int columnas;
        int filas;

        System.out.println("Escribe el numero de Filas");
        filas = pedir.nextInt();

        System.out.println("Escribe el numero de Columnas");
        columnas = pedir.nextInt();

        int[][] numPrimos = new int[filas][columnas]; // Lo correcto es filas x columnas, no viceversa como lo tenías

        pedir.close(); // Cerrar Scanner

        for (int i = 0; i < numPrimos.length; i++) {
            for (int j = 0; j < numPrimos.length; j++) {
                if (i == 0 && j == 1) { // Guarda: 1
                    break;
                }

                if (i == 1 && j == 2) { // Guarda: 1 2
                    break;
                }

                if (i == 2 && j == 3) { // Guarda: 1 2 3
                    break;
                }

                numPrimos[i][j] = j + 1;
            }

        }

        for (int i = 0; i < numPrimos.length; i++) {
            for (int j = 0; j < numPrimos.length; j++) {
                System.out.print(numPrimos[i][j]);
            }
            System.out.print("\n");
        }

    }
}

Result:

  

1000

     

1200

     

1230

     

1234

    
answered by 05.03.2018 в 15:31