2

I'm looking to print out a number matrix using parallel arrays. I want to find a way to ensure that each number is printed out with a proper amount of digits, based on how long the longest digit number in the array is.

So for example:

rows = r;
cols = c;
int[][] matrix = new int[rows][cols];

for (int x = 0; x < cols; x++)
{
  for (int y = 0; y < rows; y++)
  {
    matrix[x][y] = (x*y);
  }
}

If I choose to set cols = 101 and rows = 101, my largest number will be 10000. How can I set this program up so that at matrix[1][1] = (1*1) my output will be 00001, instead of just 1?

Ashot Karakhanyan
  • 2,734
  • 3
  • 21
  • 28
  • What you can do is after creating your 2D int array, you can then create an identicle array, but of type String. That way you could buffer the values with zeroes in accordance with the number of digits you want to display. – Alan Mar 07 '14 at 22:54

2 Answers2

0

Use String.format:

String.format("%05d", num)

The 0 means pad with 0s, and the 5 means set the width to 5, so that 00001 will be printed instead of 1.

To make it work for all row and column lengths, do this:

int width = (int) Math.log10((rows-1)*(cols-1)) + 1;
String.format("%0"+width+"d", num);

width calculates the number of zeros in the maximum value in the number matrix by taking the log base 10 of it. For example, log(10) = 1. So the width of all numbers should be width + 1;

fvrghl
  • 3,331
  • 4
  • 25
  • 34
0
int rows = 101;
int cols = 101;
int padLen = String.valueOf(rows * cols).length();
String[][] matrix = new String[rows][cols];

for (int x = 1; x < cols; x++) {
  for (int y = 1; y < rows; y++) {
    matrix[x][y] = String.format("%0" + padLen + "d", x*y);
  }
}
DanArl
  • 1,043
  • 8
  • 10