Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hello, I need guidance to come up with a java method for my matrix class. The me

ID: 3649026 • Letter: H

Question

Hello, I need guidance to come up with a java method for my matrix class. The method returns a String with all the elements of the matrix.Each row is on a seperate line. Spacing is based on longest element in the Matrix and each row starts and ends with a vertical bar '|'.

So say I have the matrix:
10 2 100
2 2 2
2 10 5

The output would be: (where the "_" represents the space, so in this case, the output should be spaced to a total of 4 positions for each number )
|_ _ 1 0 _ _ _ 2 _ 1 0 0|
|_ _ _ 2 _ _ _ 2 _ _ _ 2|
|_ _ _ 2 _ _ 1 0 _ _ _ 5|

If the matrix were to chance to:
10 2 100
2 2 2
2 10 -5

output would be: (negative instead of space)
|_ _ 1 0 _ _ _ 2 _ 1 0 0|
|_ _ _ 2 _ _ _ 2 _ _ _ 2|
|_ _ _ 2 _ _ 1 0 _ _ - 5|

I know, I have to find and compare the largest and smallest number in order to come up with the number pf positions needed for each string.

I just don't know where to begin? Could anyone please explain a step by step process on how to get this output???

Explanation / Answer

please rate - thanks

import java.util.*;
    public class matrix
   {public static void main(String[] args)
      {int mat[][]={{10,2,100},{2,2,2},{2,10,5}};
       String output;
        output=formatMatrix(mat);   
        System.out.println(output);   
                  }
public static String formatMatrix(int mat[][])
{String out="";
int i,j, max=0,chars=0;
for(i=0;i<mat.length;i++)
    for(j=0;j<mat[0].length;j++)
         if(mat[i][j]>max)
              max=mat[i][j];
chars=countDigits(max)+1;
for(i=0;i<mat.length;i++)
     {out=out+"|";
    for(j=0;j<mat[0].length;j++)
           out=out+formatIt(mat[i][j],chars);
    out=out+"| ";
     }
return out;
}
public static String formatIt(int n,int c)
{String o="";
int i;
int m=countDigits(n);
int spaces=c-m;
for(i=0;i<spaces;i++)
    o=o+" ";
o=o+n;

return o;
}
public static int countDigits(int n)
{int count=0;
while(n>0)
   {count++;
    n/=10;
    }
return count;
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote