Formatting 2d Array Output
I was wondering if there is a way to format the output of an array so that each indexed item has a discriptor and formatted in a certian way?
Example:
I have an array with 2 rows and 2 columns filled with numbers = double[][] numberArray = new double[2][2];
sample data
[0][0] = 1
[0][1] = 1
[1][0] = 2
[1][1] = 2
When I run my for loops my output statement is:
for (int i=0; i<ROWS; i++)
{
for (int j=0; j<COLUMNS; j++)
{
System.out.print(" " + numberArray[i][j]);
}
This will output something like this:
1.0 1.0
2.0 2.0
I would like to format the output to look like this:
Day 1 Earnings $ 1.00
Day 2 Earnings $ 2.00
If I try the System.out.printf(.......); I can only put one discriptor and one format for both columns. I would like to format each column seperately from each other.
Could you please point me in the right direction?
Thanks,
DS
Re: Formatting 2d Array Output
Please post the code you are having problems with. The printf() method should be able to print multiple values on multiple lines.
Re: Formatting 2d Array Output
The code that I need help with is:
for (int i=0; i<ROWS; i++)
{
for (int j=0; j<COLUMNS; j++)
{
System.out.print(" " + numberArray[i][j]);
}
The problem is when I use the printf to format I don't know how to insert a discriptor in front of each column and format the numbers that are stored in the array.
Here is an example:
System.out.printf("Day %5.0f", numberArray[i][j]);
it will output this:
Day 1 Day 2
I would like to make a format statement that would allow me to format for the [0][0] and then another format for [0][1] and all the way down the array.
Thanks,
DS
Re: Formatting 2d Array Output
Something like this?
System.out.printf("Day %5.0f <Descriptor here> %5.0f\n", numberArray[i][j], numberArray[i][j+1]);
Re: Formatting 2d Array Output
Thank you so much.
I put in what you had up top and it would print the first line perfectly but it threw an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at arraywork.ArrayWork.main(ArrayWork.java:36)
Java Result: 1
I added a -1 behind the COLUMNS and now it works perfectly.
Thank you
Re: Formatting 2d Array Output
My code was not intended to be usable as posted. It was just an idea of how to do it.