人!
首先,我来自巴西,很抱歉,如果我犯了一些语法错误。
我遇到了解决问题的问题,我必须使用一个程序,该程序在java中生成具有用户通知维度的matix。然后,它必须用矩阵填充矩阵,这些值也由用户输入。我的代码停在我的第二个运行,通过列。我得到一个ArrayIndexOutOfBoundException。你能帮我看看我做错了吗?
import java.util.Scanner;
public class DiagonalsSum {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[][] matrix;
int[] sizes = new int[2];
int diagonalsSum = 0, i, j, n, m;
for(i = 0; i < 2; i++){
n = i + 1;
System.out.println("Inform the " + n + " dimension of the matrix");
sizes[i] = s.nextInt();
}
matrix = new int[sizes[0]][sizes[1]];
for(i = 0; i < matriz.length; i++){
n = i + 1;
System.out.println(n);
for(j = 0; j < matrix[sizes[0]].length; j++){
m = j = 1;
System.out.println("Inform the value of " + n + "." + m +
" in the matrix:");
matrix[i][j] = s.nextInt();
}
}
s.close();
i = 0;
j = 0;
while(i < matrix.length && j < matrix[sizes[1]].length){
diagonalsSum += matrix[i][j];
i++;
j++;
}
i = 0;
j = (matrix[sizes[i]].length - 1);
while(i < matrix.length && j > 0){
diagonalsSum += matrix[i][j];
i++;
j--;
}
System.out.println("The sum of the primary and secondary diagonals is " + diagonalsSum);
}
先谢谢你,伙计们!
答案 0 :(得分:0)
试试这个:
for(i = 0; i < matrix.length; i++){
matrix[i] = new int[sizes[1]];
n = i + 1;
System.out.println(n);
for(j = 0; j < matrix[sizes[0]].length; j++){
m = j = 1;
System.out.println("Inform the value of " + n + "." + m +
" in the matrix:");
matrix[i][j] = s.nextInt();
}
}
Java是一种面向对象的语言。如果您在正确的Matrix
类中封装所需的行为,那么您会做得更好。
答案 1 :(得分:0)
我认为这里有一些错误,但我会解决你所询问过的错误。
我相信
for(j = 0; j < matrix[sizes[0]].length; j++)
因为你已经宣布:,所以总是会超出范围
matrix = new int[sizes[0]][sizes[1]];
请注意,Java具有基于0的索引,这意味着对于任何数组,array[array.length]
都将超出范围。这种类型的访问实际上是你的for循环所做的。
for(j = 0; j < matrix[sizes[0]-1].length; j++)
应修复列循环问题。
答案 2 :(得分:0)
人!
我改变了一些事情并且有效!
感谢您的帮助!
import java.util.Scanner;
public class DiagonalsSum {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[][] matrix;
int[] sizes = new int[2];
int diagonalsSum = 0, i, j, n, m;
for(i = 0; i < 2; i++){
n = i + 1;
System.out.println("Inform the " + n + " dimension of the matrix");
sizes[i] = s.nextInt();
}
matrix = new int[sizes[0]][sizes[1]];
for(i = 0; i < sizes[0]; i++){
n = i + 1;
System.out.println(n);
for(j = 0; j < sizes[1]; j++){
m = j = 1;
System.out.println("Inform the value of " + n + "." + m +
" in the matrix:");
matrix[i][j] = s.nextInt();
}
}
s.close();
i = 0;
j = 0;
while(i < sizes[0] && j sizes[1]){
diagonalsSum += matrix[i][j];
i++;
j++;
}
i = 0;
j = (sizes[1] - 1);
while(i < sizes[0] && j > -1){
diagonalsSum += matrix[i][j];
i++;
j--;
}
System.out.println("The sum of the primary and secondary diagonals is " + diagonalsSum);
}