我正在使用此代码:
import java.util.Scanner;
import java.util.Arrays;
import java.util.Random;
public class Matrix
{
public static void main(String[] args)
{
Scanner enter = new Scanner(System.in);
int[][] firstMatrix = new int[4][4];
int[][] secondMatrix = new int[4][4];
Random spin = new Random();
System.out.println("Please enter 16 numbers to populate the array: ");
for (int count = 0; count<firstMatrix.length;count++) // nested for for user input to populate 4x4 array
{
for (int count2 = 0; count2 < firstMatrix[count].length; count2++)
{
firstMatrix[count][count2] = enter.nextInt(); // populate array with user input
}
} // end array population
System.out.printf("The sum is: %d%n", sumMatrix(firstMatrix)); // call sumMatrix
System.out.println(firstMatrix[0][0]); // debug
for (int count3 = 0; count3<secondMatrix.length; count3++) // nested for to populate array with random numbers 1-100, row
{
for (int count4 = 0; count4<secondMatrix[count3].length; count4++) // column
{
secondMatrix[count3][count4] = 1 + spin.nextInt(100); // 100 inclusive, generate and populate array
}
}
System.out.println(secondMatrix[0][0]); // debug to show that it is properly printing the correct element
for (int i = 0; i<secondMatrix.length; i++)
{
for (int j = 0; j<secondMatrix[i].length; j++)
System.out.print(" " + secondMatrix[i][j]); // print the total array ( this process can be used to print the returned array )
}
System.out.println(); // debug
int arrayTotal = firstMatrix[0][0] + secondMatrix[0][0]; // debug
System.out.println("The element total is " + arrayTotal); // debug
System.out.println();
addMatrix(firstMatrix,secondMatrix); // call addMatrix
System.out.println("Programmed by Stephen Mills");
} // end main
public static int sumMatrix(int[][] array) // method to sum the elements of the array
{
int total = 0;
for (int number = 0; number<array.length; number++) // row
{
for (int number2 = 0; number2<array[number].length; number2++) // column
total += array[number][number2]; // sum of all elements
}
return total; // returns the sum
} // end sumMatrix
public static int[][] addMatrix(int[][] array1, int[][] array2) // improper method
{
int[][] thirdMatrix = new int[4][4];
for (int count4 = 0; count4<thirdMatrix.length; count4++)
{
for (int count5 = 0; count5<thirdMatrix[count4].length; count5++)
thirdMatrix[count4][count5] = array1[count4][count5]+array2[count4][count5];
}
System.out.println(Arrays.toString(thirdMatrix));
return thirdMatrix;
} // end addMatrix7
}
大多数程序按预期工作,但我得到这个“[I @ 3d4eac69,[I @ 42a57993,[I @ 75b84c92,[I @ 6bc7c054]输出时尝试打印我的数组。我已经尝试了几种方法,包括简单的println,toString,设置一个等于方法调用的变量,我尝试将print语句放在main中,然后放在方法第二位。任何想法为什么会发生这种情况?
答案 0 :(得分:0)
如果要打印二维数组thirdMatrix的int元素,可以尝试:
for(int[] simpleArray: thirdMatrix)
System.out.println(Arrays.toString(simpleArray));
输出的原因:当你打电话时
Arrays.toString(thirdMatrix)
你会打电话
String.valueOf(element)
第三个矩阵的foreach元素。由于thirdMatrix的元素是Array而不是基本类型,因此方法
String.valueOf(Object obj)
将调用返回thirdMatrix元素的哈希码(一维数组)。