0
Hello, I’m doing this exercise, but I’m having a hard time. Follow the statement:
22) Write a program to generate one matrix (N x M) (<=20) and another (N x P) (<=20). Generate a third matrix (N x (M+P)) (<=20 x <=40), where for each interleave row their respective columns and present the three matrices.
Here’s the code I already have:
import java.util.Scanner;
public class Ex22 {
public static void main(String args[]) {
Scanner leia = new Scanner(System.in);
int n, a = 0, b = 0;
do {
System.out.printf("Entre com o tamanho da matriz: ");
n = leia.nextInt();
} while (n > 20);
int [][] m = new int [n][n];
System.out.printf("\nMatriz M:\n");
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
m[i][j] = (int)(Math.random() * 9+1);
System.out.printf("%d ", m[i][j]);
}
System.out.printf("\n");
}
do {
System.out.printf("\nEntre com o tamanho da matriz: ");
n = leia.nextInt();
} while (n > 20);
int [][] p = new int [n][n];
System.out.printf("\nMatriz P:\n");
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
p[i][j] = (int)(Math.random() * 9+1);
System.out.printf("%d ", p[i][j]);
}
System.out.printf("\n");
}
int [][] q = new int [n][n+n];
System.out.printf("\nMatriz Q:\n");
for(int i=0; i<n; i++){
for(int j=0; j<(n+n); ){
q[i][j] = m[i][a];
a++;
j++;
q[i][j] = p[i][b];
b++;
j++;
}
}
for(int i=0; i<n; i++){
for(int j=0; j<(n+n); j++){
System.out.printf("%d ", q[i][j]);
}
System.out.printf("\n");
}
}
}
Does anyone know why it’s popping?
Anybody know why it’s popping? This is the error that returns: Matrix Q: Exception in thread "main" java.lang.Arrayindexoutofboundsexception: 2 At Ex22.main(Ex22.java:53) But in C it compiles without errors.
– Michael Martins
You don’t reset
a
andb
no for matrix q, I did not analyze the rest of the code, but you are considering that n = m = p and that is not what the question asks too...– Felipe Avelar
Michael Martins, compiling it compiles normally, but between compiling and executing there is a huge difference.
– Victor Stafusa