gpt4 book ai didi

java - 将自定义二维数组打印为矩阵

转载 作者:行者123 更新时间:2023-12-01 13:25:44 25 4
gpt4 key购买 nike

鉴于我当前的代码,我如何以矩阵格式输出它?我当前的输出方法只是以直线列出数组。不过,我需要将它们堆叠在相应的输入参数中,以便 3x3 输入产生 3x3 输出。谢谢!

import java.util.Scanner;

最佳答案

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();
}

关于java - 将自定义二维数组打印为矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21815820/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com