如何将元素按行添加到矩阵中,用空格分隔



考虑一个大小为N x N的正方形矩阵a和一个索引(x,Y(。编写程序打印商Q,当和A的对角线元素的和除以A[X][Y]的一位数和。考虑从开始的对角线A[0][0]。一个数字的一位数和是重复进行的a[X][Y]的位数和,直到找到一个位数。从STDIN读取输入,并将输出打印到STDOUT。在读取输入或在打印时,因为这些有助于标准输出。

限制条件:

I) 1 < N <= 35
II) 0 <= X, Y < N

输入格式:

  • 输入的第一行包含N
  • 接下来的N行输入分别包含N个整数,由一个空格分隔
  • 输入的最后一行包含由一个白色分隔的X和Y空间

输出格式:

  • 输出包含Q

样本输入1:

3
11 22 33
44 55 66
77 88 99
1 1

样本输出1:

165

我刚开始告诉我哪里错了。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class matrix {
static BufferedReader bi = new BufferedReader(new InputStreamReader(System.in));
static String[] a;
static int[] a1;

public static void stringar() throws IOException {

a =bi.readLine().split(" ");
a1=new int[a.length];
for(int i1=0;i1<a.length;i1++) {
a1[i1]=Integer.parseInt(a[i1]);
}
}
public static void main(String args[]) throws Exception{
int i = 0,j = 0,N,sum=0;
N = bi.read();
int[][] mat = new int[N][N];

System.out.println("Enter the elements of the matrix") ;
stringar();
for (int k = 0; k < N; k++) {
if(k==N&&i==N) {
break;
}
if(j==N) {
k=0;
j=0;
i++;
stringar();
continue;
}
mat[i][j]=a1[k];
j++;

}

System.out.println("The elements of the matrix") ;
for(i=0;i<N;i++)
{ 
for(j=0;j<N;j++)
{ 
System.out.print(mat[i][j]+"t");
}
System.out.println("");
}
for(i=0;i<N;i++)
{ 
for(j=0;j<N;j++)
{ 
if(i==j)    //this condition checks for diagonal
{
sum = sum + mat[i][j];
}
}
}
System.out.print("SUM of DIAGONAL elements of the matrix = "+sum) ;
}   
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
class DiagonalSumOfMatrix{
static int N=0;enter code here
static int[]arr()throws IOException{
BufferedReader bi = newBufferedReader(newInputStreamReader(System.in));
String[]strNums;
strNums = bi.readLine().split(" ");
int num[] = new int[strNums.length];
for (int i = 0; i < strNums.length; i++) {
num[i] = Integer.parseInt(strNums[i]);
}
return num; 
}
public static void main(String[] args) throws IOException{
Scanner sc= new Scanner(System.in);
N=sc.nextInt();
int num[]=new int[N];
int[][] mat = new int[N][N];
for (int i = 0; i < num.length; i++) {
num= arr();                                                                                         
for (int j = 0; j < N; j++) {
mat[i][j]=num[j];
}
}
sc.close();
int sum=0;
for(int i=0;i<N;i++) { 
for(int j=0;j<N;j++) { 
if(i==j) {
sum = sum + mat[i][j];
}
}
}
System.out.println(sum);
}
}

最新更新