鉴于我目前的代码,如何以矩阵格式输出?我当前的输出方法只是直线列出数组。但是我需要将它们堆叠在相应的输入参数中,因此3x3输入会产生3x3输出。谢谢!
import java.util.Scanner;
答案 0 :(得分:1)
for(int row = 0; row < rows; row++){
for( int column = 0; column < columns; column++){
System.out.print(array2d[row][column] + " ");
}
System.out.println();
}
这将打印出一行一行,然后移到下一行并打印出其内容等等......使用您提供的代码进行测试并运行。
编辑 - 添加了您想要的代码:
public static void main(String[] args) {
Scanner scan =new Scanner(System.in); //creates scanner object
System.out.println("How many rows to fill?"); //prompts user how many numbers they want to store in array
int rows = scan.nextInt(); //takes input for response
System.out.println("How many columns to fill?");
int columns = scan.nextInt();
int[][] array2d=new int[rows][columns]; //array for the elements
for(int row=0;row<rows;row++)
for (int column=0; column < columns; column++)
{
System.out.println("Enter Element #" + row + column + ": "); //Stops at each element for next input
array2d[row][column]=scan.nextInt(); //Takes in current input
}
System.out.println(Arrays.deepToString(array2d));
String[][] split = new String[1][rows];
split[0] = (Arrays.deepToString(array2d)).split(Pattern.quote("], [")); //split at the comma
for(int row = 0; row < rows; row++){
System.out.println(split[0][row]);
}
scan.close();
}
答案 1 :(得分:0)
for (int i =0; i < rows; i++) {
for (int j = 0; j < columns ; j++) {
System.out.print(" " + array2d[i][j]);
}
System.out.println("");
}