Pretendo passar um vetor para uma matriz. Este é o codigo que eu criei, mas quando crio um vetor com os valores: 1, 2, 3, 4, 5, 6, 7, 8, 9
a matriz fica da seguinte forma:
1 0 3
1 0 3
1 0 3
quando devria ficar assim:
1 2 3
4 5 6
7 8 9
Aqui esta o codigo:
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner ler1 = new Scanner(System.in);
System.out.println("Introduza os valores: ");
String stringDeNumeros = ler1.nextLine();
// converte a string para um vetor de strings
String[] vetorString = stringDeNumeros.split(",");
int vetorInt[] = new int[vetorString.length];
// converte de string para inteiros
try {
for(int i = 0; i < vetorString.length; ++i) {
vetorInt[i] = Integer.parseInt(vetorString[i]);
}
}catch(NumberFormatException e){
System.out.println("Erro: Não introduziu apenas numeros! " + e);
}
double ordemMatriz=Math.sqrt(vetorInt.length);
int ordem=(int)ordemMatriz;
int M[][]= new int[ordem][ordem];
for(int i = 0; i<ordemMatriz; i++) {
for(int j = 0; j<ordemMatriz; j++){
M[i][j]=vetorInt[j];
j++;
}
}
for (int l = 0; l < M.length; l++) {
for (int c = 0; c < M[0].length; c++) {
System.out.print(M[l][c] + " "); //imprime caracter a caracter
}
System.out.println(" "); //muda de linha
}
class Teste {
public static void main(String[] args) {
String stringDeNumeros = "1, 2, 3, 4, 5, 6, 7, 8, 9";
// converte a string para um vetor de strings
String[] vetorString = stringDeNumeros.split(",");
int vetorInt[] = new int[vetorString.length];
// converte de string para inteiros
try {
for (int i = 0; i < vetorString.length; ++i) {
vetorInt[i] = Integer.parseInt(vetorString[i].trim());
}
} catch (NumberFormatException e) {
System.out.println("Erro: Não introduziu apenas numeros! " + e);
}
double ordemMatriz = Math.sqrt(vetorInt.length);
int ordem = (int) ordemMatriz;
int[][] M = new int[ordem][ordem];
int counter = 0;
for (int i = 0; i < ordem; i++) {
for (int j = 0; j < ordem; j++) {
M[i][j] = vetorInt[counter++];
}
}
for (int l = 0; l < M.length; l++) {
for (int c = 0; c < M[0].length; c++) {
System.out.print(M[l][c] + " "); // imprime caracter a caracter
}
System.out.println(" "); // muda de linha
}
}
}