Problemas com Matriz

9 respostas
B

Estou fazendo um exercicio em java sou iniciante. Para o livro é um exercicio nivel basico mas eu não sei se está certo.
O exercicio pede (“Escreve um programa que a partir de um universo de números de 1 a 60, gere e imprima 10 sequencias aleatórias de 6 numeros e os armazene em uma matriz com 10 linhas e 6 colunas”) O código q eu gere está abaixo

public class Vetor {
   public static void main (String args[]) {
         System.out.println ("\n\n\t\tPrograma Vetor\n\n");
         int numeros[][] = new int[10][6];
	 int maximo = 60;

	 // preenchendo a matriz

		
	 for (int i=1; i<= 6; i++)
       	 {
         
	   int numero = (int) (Math.random() * maximo);
	   int numero1 = (int) (Math.random() * maximo);
	   int numero2 = (int) (Math.random() * maximo);
	   int numero3 = (int) (Math.random() * maximo);
	   int numero4 = (int) (Math.random() * maximo);
	   int numero5 = (int) (Math.random() * maximo);
	   int numero6 = (int) (Math.random() * maximo);
	   int numero7 = (int) (Math.random() * maximo);
	   int numero8 = (int) (Math.random() * maximo);
	   int numero9 = (int) (Math.random() * maximo);
		 
	 for (int j=1; j<numeros.length; j++)
 	 {
	    for (int k=1; k<numeros[j].length; k++)
	    {
	       numeros [j][k] = j*k;
	      
	    }
	 }
	   System.out.print (numero + " ");
	   System.out.print (numero1 +" ");
	   System.out.print (numero2 +" ");
	   System.out.print (numero3 +" ");
	   System.out.print (numero4 +" ");
	   System.out.print (numero5 +" ");
	   System.out.print (numero6 +" ");
	   System.out.print (numero7 +" ");
	   System.out.print (numero8 +" ");
	   System.out.println (numero9 +" ");
	 }
	    
   }
}

Está certo???

9 Respostas

p5f8

Olá BurnGirl,

Está certo o que fez, agora só falta armazenar os valores das variáveis numero, numero1, …, numero9 na matriz…

C
Cara nao q esteja errado, mas quando for fazer uma classe tem seguir alguns padroes da programaçao orientada a objetos.Veja:

[]

import <a href="http://java.io">java.io</a>.*;

public class Vetor

{

//declare as variaveis de sua classe

private int maximo;

private int linha;

private int coluna;

private int[][] numero;

//faça um construtor para sua class- este eh o padrao

public Vetor()

{

linha =10;

coluna =6;

maximo = 60;

numero = new int[linha][coluna];

}

//outro construtor da classe

public Vetor(int linha,int coluna,int max)

{

this.linha =linha;

this.coluna =coluna;

maximo = max;

numero = new int[linha][coluna];
}

// um metodo get e um set para cada variavel

public int getMaximo()

{

return maximo;

}

public int getLinha()

{

return linha;

}

public int getColuna()

{

return coluna;

}

public int[][] getNumero()

{

return numero;

}

public void setLinha(int i)

{

linha=i;

}

public void setColuna(int i)

{

coluna = i;

}

public void setMaximo(int max)

{

maximo = max;

}

// um metodo q monta a matriz

public void fazMatriz()

{

for (int i=0;  i < linha; i++)

{

for (int j=0; j< coluna; j++)

{

numero [i][j] = (int) (Math.random() * maximo);

}

}

}

// um metodo q imprime a matriz

public void imprime()

{

System.out.print ("\n\nMatriz com numeros aleatórios\n\n");

for (int i=0;  i < linha; i++)

{

for (int j=0; j< coluna; j++)

{

System.out.print (numero[i][j] + "  “);

}

System.out.print (”\n");

}

}

// metodo para executar o programa

public static void main(String args[])

{

Vetor vetor = new Vetor(); // instancia sua classe com construtor    padrao

vetor.fazMatriz(); // monta a matriz

vetor.imprime();// imprime a matriz

}

}



Falow ateh +

Carlos Martins

wandersonxs

Relax Carlos… o rapaz ta aprendendo e tá perdido pq tudo eh novo e vc já dá um tiro de OO na cara dele… :shock: :shock: :shock:
Assim até eu ficaria assustado com o Java. 8)

Aprenda a sintaxe, depois q se sentir confortável com ela… aprenda OO.

Abraços
Wanderson :stuck_out_tongue:

B

Olá pessoal obrigada as dicas, Vou tentar entender o funcionamento e preencher as matrizes com os numeros, mas pelo q eu vi eu ja fiz isso ou não???

B

Pessoal me ajudem, to com esse problema de gerar numeros aleatrios e colocar numa matriz [10][6] e naiio estou conseguindo fazer e muito menos entender como fazer.

(editado por cv: nao precisa GRITAAAAAAR! :))

cv1

O que vc nao esta entendendo? Vejamos...

Declarar um array 10x6:
int myArray = new int[10][6];
Inicializar um array 10x6:
for(int i=0; i<myArray.length; i++) {
  for(int j=0; j<myArray[i].length; j++) {
    // ...
  }
}
Obter um numero aleatorio (maximo eh um int contendo o maximo):
myArray[i][j] = (int) (Math.random() * maximo);

Juntando os pedacos...

int myArray = new int[10][6];

for(int i=0; i<myArray.length; i++) {
  for(int j=0; j<myArray[i].length; j++) {
    myArray[i][j] = (int) (Math.random() * maximo);
  }
}

O que falta?

B

Olá desculpa ai fiquei um pouco brava com esse código q eu num tava entendendo, mas ainda num to entendendo muito bem reparem o código q eu fiz abaixo. Eles ja está preenchendo a matriz e imprimindo na tela???
Como eu faço pra imprimir na tela a sequencia de forma correta por exemplo:
Imprimir na tela desse jeito.
15 25 36 45 25 36
65 30 58 96 36 41

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

      int matriznum[][] = new int[10][6];
            
      int maximo = 60;
   

	for (int j=0; j < matriznum.length; j++)
	{
	   for (int k=0; k < matriznum[j].length; k++)
	   {
	        matriznum[j][k] = j*k;
		matriznum[j][k] = (int) (Math.random() * maximo);
	        System.out.print(matriznum[j][k]+ " ");
	   	
		
	   }
	}

   }
}
cv1

Voce precisa separar a hora de preencher a matriz e a hora de mostrar a matriz na tela. Por exemplo, com a matriz preenchida, vc pode fazer assim:

for(int i=0;i<matriz.length;i++) { for(int j=0; j<matriz[i].length;j++) { System.out.print(matriz[i][j]+ " "); } System.out.println(); // imprime uma linha em branco }

B

Valeu amigo, um dia vou ser crânio assim. Mas eu tava pensando em fazer uma melhoria nele, queria ordenar como eu tenho q proceder??? Criar um outro for? Declarar mais variaveis??? Onde eu posiciono???

Criado 27 de maio de 2005
Ultima resposta 29 de mai. de 2005
Respostas 9
Participantes 5