我有一个任务,要求用户输入二维数组的大小,然后询问数组中的数字,然后进行一些计算(如总和& max) 。 我遇到麻烦的是,当它向用户询问数组中的数字时,我无法对它进行格式化,以便按照它应该分配的方式进行格式化。在显示最终数组的格式时也遇到麻烦,它也应该处于这种状态。Java中的2D阵列打印格式
实施例用于用户输入:
输入[0] [0]:
输入[0] [1]:
等等
实施例用于阵列天线的最终显示:
[1,2,3]
[4,5,6]
等
这是我的代码到目前为止,我已经评论了我需要帮助的部分。
import java.util.Arrays;
import java.util.Scanner;
class Array2DMethods {
public static int[][] readInputs() {
Scanner keyboard = new Scanner(System.in);
System.out.print(" How many rows? ");
int rows = keyboard.nextInt();
System.out.print(" How many columns? ");
int columns = keyboard.nextInt();
int[][] ret = new int[rows][columns];
for (int i = 0; i < ret.length; i++) {
for (int j = 0; j < ret[i].length; j++) {
/*Need to format it like this: Enter [0][0]:
Enter [0][1]:
etc. until it forms the 2D Array but not sure how to get
it to print out like that.
*/
System.out.print(" Enter " + ret + ": ");
ret[i][j] = keyboard.nextInt();
}
}
return ret;
}
public static int max(int[][] anArray) {
int ret = Integer.MIN_VALUE;
for (int i = 0; i < anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
if (anArray[i][j] > ret) {
ret = anArray[i][j];
}
}
}
return ret;
}
public static void rowSum(int[][] anArray) {
int rows = anArray.length;
int cols = anArray[0].length;
int[] sum = new int[rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sum[i] += anArray[i][j];
}
}
for (int x = 0; x < anArray.length; x++) {
System.out.println("Sum of row " + x + " = " + sum[x]);
}
}
public static void columnSum(int[][] anArray) {
int rows = anArray.length;
int cols = anArray[0].length;
int[] sum = new int[cols];
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
sum[i] += anArray[j][i];
}
}
for (int x = 0; x < anArray.length || x > anArray.length; x++) {
System.out.println("Sum of columnn " + x + " = " + sum[x]);
}
}
public static boolean isSquare(int[][] anArray) {
for (int i = 0, l = anArray.length; i < l; i++) {
if (anArray[i].length != l) {
return false;
}
}
return true;
}
public static void displayOutputs(int[][] anArray) {
System.out.println("Here is your 2Dim Array:");
for (int i = 0; i < anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
System.out.print(anArray[i][j]);
/*When displaying the whole array before the end of the program
it needs to be formatted like this:
[1,2,3]
[4,5,6]
[7,8,9]
but I'm not sure how to get it to print like that.
*/
System.out.print(", ");
}
System.out.println();
}
}
}
class Arrays2DDemo {
public static void main(String[] args) {
System.out.println("Let's create a 2Dim Array!");
int[][] anArray = Array2DMethods.readInputs();
Array2DMethods.max(anArray);
System.out.println();
Array2DMethods.rowSum(anArray);
System.out.println();
Array2DMethods.columnSum(anArray);
Array2DMethods.isSquare(anArray);
System.out.println("\nIs this a square array? " + Array2DMethods.isSquare(anArray));
System.out.println();
Array2DMethods.displayOutputs(anArray);
}
}
感谢任何帮助,您可以给我。
感谢它的工作。 – 2014-12-03 21:38:00