将多维 Java 数组转换为字符串矩阵?

发布于 2024-09-30 21:52:35 字数 2783 浏览 3 评论 0原文

我似乎无法让这个 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();
}
}

感谢您的帮助! :)

I can't seem to get this toString() method to work? The deepToString method works perfectly, except that I have to print them out in an organized way, like a matrix would look like with aligned rows and columns. I had it working a while ago, but I changed something and now god knows what I did, I have no idea how to get it back. Anyhow, does anyone know how to output a multidimensional array to matrix like string form?

Also, another issue I am having is figuring out how to check if the numbers >= 0, because they can't be negative. Not sure how to do that? Thought I could store each value as it loops and check if it's negative, but I just keep getting confused and/or running into errors. Any help regarding these issues would be greatly appreciated, I have been working on this for like 5hrs and have not gotten anywhere! _

Here is the code I have so far:

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

Thank you for all your help! :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

如何视而不见 2024-10-07 21:52:35

您的 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;
}

旁注,在您的 add 函数中就行当你说for (int j = 0; j < A[1].length; j++) {时,如果你的矩阵是1xN,你可能会遇到问题。在Java中,数组是从0开始索引的,第一行是0,而不是1。对您来说,通常更安全的方法是执行我在这两个代码示例中所示的操作,并使用 A[i].length ,因为您可以根据您的 fori 上索引的循环表明 A 的第 i 行存在。

Your toString method will not print the second dimension, you need two for loops:

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

To check all the numbers in a given matrix are non-negative, you again need to iterate through every element in the matrix. In the case where any number is negative, you can immediately return, if you get through the whole matrix without finding any negatives, then there are none:

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

On a side note, in your add function on the line where you say for (int j = 0; j < A[1].length; j++) {, you might have a problem if your matrix is 1xN. In Java, arrays are 0-indexed, the first row is 0, not 1. A generally safer approach for you would be to do what I've shown in these two code samples and use A[i].length as you're assured based on your for loop indexed on i that the i-th row of A exists.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文