給出n階方陣里所有數,求方陣里所有數的和
輸入描述:
輸入有多個測試用例
每個測試用例第一個第一個整數n n<=1000 表示方陣階數為n
接下來是n行的數字,每行n個數字用空格隔開
輸出描述:
輸出一個整數表示n階方陣的和
例子:
輸入
3
1 2 3
2 1 3
3 2 1
輸出
18
查看代碼
import java.util.*;
public class Demo2 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){ //保證有多組輸入數據
int n = Integer.parseInt(sc.nextLine());
int sum = 0;
for(int i = 0; i < n; i++){
String[] split = sc.nextLine().split(" ");
for(int j = 0; j < n; j++){
sum += Integer.parseInt(split[j]);
}
}
System.out.println(sum);
}
}
}
總結:每一行數據的處理並不需要定義一個int型數組,直接轉換數據類型累加和即可,因為這里只是將所有數據求和。