解法思路:
直接用两个for循环实现在接收数组元素的同时将元素输出。
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
int[][] a = new int[n][m];
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
a[i][j] = scan.nextInt(); //输入元素
System.out.print(a[i][j]+ " "); //输出元素
}
System.out.println(); //换行
}
}
}
优化后的代码,这个优化在解题思路上并没有什么创新,只是代码运行时间和内存得到一定的优化。只是要注意这种解法引入了count
作为一个累加器。
import java.io.*;
public class Main{
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] str = br.readLine().split(" ");
int n = Integer.parseInt(str[0]);
int m = Integer.parseInt(str[1]);
str = br.readLine().split(" ");
int[][] a = new int[n][m];
int count = 0;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
a[i][j] = Integer.parseInt(str[count]);
System.out.print(a[i][j]+ " ");
count++;
}
System.out.println();
}
}
}
另一种解题思路:
利用str = br.readLine().split(" ");
获取数组中的元素,然后用一个上界为数组长度的for循环来输出元素,如果遇到输出元素的列数等于矩阵的列数,则输出元素后换行,这样便能输出一个矩阵。
import java.io.*;
public class Main{
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] str = br.readLine().split(" ");
int n = Integer.parseInt(str[0]); //矩阵行数
int m = Integer.parseInt(str[1]); //矩阵列数
str = br.readLine().split(" "); //获取数组中的元素
for(int i = 0; i < str.length; i++){
if((i + 1) % m == 0){ //如果列数与m相等,则输出元素并换行
System.out.println(str[i] + " ");
}else {
System.out.print(str[i] + " ");
}
}
}
}