How to insert the size of an array according to user input?

2

How do I insert, asking the user through the class Scanner , the size of the array and it tells me the numbers of columns and rows you want, and then print the values, without using methods? I've tried but it's giving error:

import java.util.Scanner;

public class Matriz {
    int matriz[][], linha, coluna;

    public Matriz(int linha, int coluna){
        matriz = new int [linha][coluna];
        this.linha = linha;
        this.coluna = coluna;
    }

    public void Inserir(){
        Scanner entrada = new Scanner(System.in);
        for(int x=0; x < linha; x++){
            for(int y=0; y < coluna; y++){
                System.out.println("matriz ["+x+"]["+y+"] =");
                matriz[x][y]= entrada.nextInt();
            }//fim for
        }//fim for
    }//fim inserir

    public void Imprimir(){
        for(int x=0; x < linha; x++){

            for(int y=0; y < coluna; y++){
                System.out.print(matriz[x][y]+"\t");
            }//fim for
            System.out.println();//apenas para quebrar linha
        }//fim for
    }

    public static void main(String [] args){
        Scanner entrada = new Scanner(System.in);
        int linha=0, coluna =0;

        System.out.println("Informe a quantidade de linhas da matriz");
        linha = entrada.nextInt();

        System.out.println("Informe a quantidade de colunas da matriz");
        coluna = entrada.nextInt();
        Matriz mat = new Matriz(linha, coluna);

        mat.Inserir();
        mat.Imprimir();
    }
}

Without using methods.

    
asked by anonymous 14.02.2016 / 01:23

1 answer

3

After instantiating an array, you can no longer change its size. If you need to set this size after user input, just boot the array, then instantiate the required data entries:

public static void main (String[] args) {
        int matriz[][];

        Scanner entrada = new Scanner(System.in);
        int linha=0, coluna =0;

        System.out.println("Informe a quantidade de linhas da matriz");
        linha = entrada.nextInt();

        System.out.println("Informe a quantidade de colunas da matriz");
        coluna = entrada.nextInt();

        matriz = new int[linha][coluna];

         for(int x=0; x < linha; x++){
            for(int y=0; y < coluna; y++){
                System.out.println("matriz ["+x+"]["+y+"] =");
                matriz[x][y]= entrada.nextInt();
            }
        }

        for(int x=0; x < linha; x++){

            for(int y=0; y < coluna; y++){
                System.out.print(matriz[x][y]+"\t");
            }
            System.out.println();
        }

    }

See working at IDEONE

In this way, the array will be created according to the total number of rows / columns reported via data entry.

    
14.02.2016 / 01:40