【发布时间】:2011-05-06 10:41:39
【问题描述】:
我似乎无法让这个 toString() 方法工作? deepToString 方法工作得很好,除了我必须以有组织的方式将它们打印出来,就像矩阵看起来像对齐的行和列一样。前一阵子我让它工作了,但我改变了一些东西,现在上帝知道我做了什么,我不知道如何取回它。无论如何,有谁知道如何将多维数组输出为字符串形式的矩阵?
另外,我遇到的另一个问题是弄清楚如何检查数字是否 >= 0,因为它们不能为负数。不知道该怎么做?以为我可以在每个值循环时存储它并检查它是否为负数,但我只是一直感到困惑和/或遇到错误。任何有关这些问题的帮助将不胜感激,我已经为此工作了 5 小时,但没有得到任何帮助! _
这是我目前的代码:
import java.util.Arrays;
public class MatrixOperations {
public static void main(String[] args) {
double[][] matrix1 = { { 0.0, 1.0, 2.0 }, { 3.0, 4.0, 5.0 },
{ 6.0, 7.0, 0.8 }, };
double[][] matrix2 = { { 1.0, 1.0, 1.0 }, { 0.0, 0.0, 0.0 },
{ 2.0, 2.0, 2.0 } };
System.out.println(toString(matrix1));
System.out.println(Arrays.deepToString(add(matrix1, matrix2)));
}
// Throws an IllegalArgumentException unless A and B contain n arrays of
// doubles, each of
// which contains m doubles, where both n and m are positive. (In other
// words, both A
// and B are n-by-m arrays.)
//
// Otherwise, returns the n-by-m array that represents the matrix sum of A
// and B.
public static double[][] add(double[][] A, double[][] B) {
if (A.length != B.length || A[1].length != B[1].length) {
throw new IllegalArgumentException("Rows and Columns Must Be Equal");
}
double[][] S = new double[A.length][A[1].length];
for (int i = 0; i < A.length; i++) {
// double valueAt = ;
for (int j = 0; j < A[1].length; j++) {
S[i][j] = A[i][j] + B[i][j];
}
}
return S;
}
// Throws an IllegalArgumentException unless A contains n arrays of doubles,
// each of
// which contains k doubles, and B contains k arrays of doubles, each of
// which contains
// m doubles, where n, k, and m are all positive. (In other words, A is an
// n-by-k array and B is a k-by-m array.)
// Otherwise, returns the n-by-m array that represents the matrix product of
// A and B.
// public static double[][] mul (double[][] A, double[][] B) {
// if (A[1].length != B.length){
// throw new IllegalArgumentException("Column-A Must Equal Row-B");
// }
// }
// Throws an IllegalArgumentException unless M contains n arrays of doubles,
// each of
// which contains m doubles, where both n and m are positive. (In other
// words, M
// is a n-by-m array.
// Otherwise, returns a String which, when printed, will be M displayed as a
// nicely
// formatted n-by-m table of doubles.
public static String toString(double[][] M) {
String separator = ", ";
StringBuffer result = new StringBuffer();
if (M.length > 0) {
result.append(M[0]);
for (int i = 0; i < M.length; i++) {
result.append(separator);
result.append(M[i]);
}
}
return result.toString();
}
}
感谢您的所有帮助! :)
【问题讨论】:
标签: java string matrix multidimensional-array