Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3321730
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T23:05:53+00:00 2026-05-17T23:05:53+00:00

I can’t seem to get this toString() method to work? The deepToString method works

  • 0

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! 🙂

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-17T23:05:54+00:00Added an answer on May 17, 2026 at 11:05 pm

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Can somebody point me to a resource that explains how to go about having
Can a LINQ enabled app run on a machine that only has the .NET
Can I get a 'when to use' for these and others? <% %> <%#
Does anyone know how can I replace this 2 symbol below from the string
I have a jquery bug and I've been looking for hours now, I can't
I have text I am displaying in SIlverlight that is coming from a CMS
Can I use the following across all browsers? <a href=# onclick=doSomething()>Click here.</a> Is this
Can anyone tell me what's wrong with this robots.txt? http://bizup.cloudapp.net/robots.txt The following is the
Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2) I have a Rails
Can I connect to a Ubuntu server, that is running MySQL using ADO.NET or

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.