【问题标题】:Convert Multidimensional Java Array to String-Matrix?将多维 Java 数组转换为字符串矩阵?
【发布时间】: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


    【解决方案1】:

    您的toString 方法不会打印第二个维度,您需要两个 for 循环:

    public static String toString(double[][] M) {
        String separator = ", ";
        StringBuffer result = new StringBuffer();
    
        // iterate over the first dimension
        for (int i = 0; i < M.length; i++) {
            // iterate over the second dimension
            for(int j = 0; j < M[i].length; j++){
                result.append(M[i][j]);
                result.append(separator);
            }
            // remove the last separator
            result.setLength(result.length() - separator.length());
            // add a line break.
            result.append("\n");
        }
        return result.toString();
    }
    

    要检查给定矩阵中的所有数字都是非负数,您需要再次遍历矩阵中的每个元素。在任何一个数为负数的情况下,您可以立即返回,如果您通过整个矩阵而没有找到任何负数,则没有:

    public static boolean isNonNegative(double[][] m){
        // iterate over first dimension
        for(int i = 0; i < m.length; i++){
            // iterate over second dimension
            for(int j = 0; j < m[i].length; j++){
                if(m[i][j] < 0){
                    // found a negative element, return immediately
                    // since this means the whole matrix cannot be
                    // called non-negative
                    return false;
                }
            }
        }
        // if we get here then no elements have been found to be negative
        // thus the matrix is non-negative.
        return true;
    }
    

    附带说明,在您说for (int j = 0; j &lt; A[1].length; j++) { 的行上的add 函数中,如果您的矩阵是1xN,您可能会遇到问题。在 Java 中,数组是 0 索引的,第一行是 0,而不是 1。对您而言,通常更安全的方法是执行我在这两个代码示例中显示的操作并使用 A[i].length,因为您可以根据在 i 上索引的 for 循环确定 i em>-第A 行存在。

    【讨论】:

    • 谢谢你,你是圣人! :)
    • 你不知道我是怎么做到的,所以如果数组中的一个元素为负数,就会抛出异常?
    • @Mr_CryptoPrime:我已经说明了如何检测一个元素是否为非负数,一旦你检测到这种情况,你可以简单地抛出一个异常。或者,您可以调用isNonNegative 并测试它的输出是否为false,如果是,您可以抛出异常。您的代码示例向您展示了如何抛出异常,因此我将这些更改留作练习。
    • 好的,再次感谢!你让我免于末期精神错乱的扩散! :)
    • 再一次,我充满了崇高的顿悟,并对您的服务表示感谢,我可能仍然是一位得救的计算机科学家。大声笑
    【解决方案2】:

    Arrays.deepToString() 怎么样?

    【讨论】:

      猜你喜欢
      • 2019-09-15
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      • 1970-01-01
      • 2019-02-13
      • 2012-11-17
      相关资源
      最近更新 更多