I am implementing a math table using two integers (a and tableSize). I have built a random operation named R. I am going to calculate a random number between the row and column range and print the random number. For those instances where the row value is larger than the column value, the output is a dash ("-").
Here is my code,
int a = 4;
int tableSize = 10;
System.out.print(" R ");
for(int i = a; i <= tableSize;i++ )
{
System.out.format("%4d",i);
}
System.out.println();
for(int i = a ;i <= tableSize;i++)
{
System.out.format("%4d ",i);
for(int j=a;j <= tableSize;j++)
{
int randomNum = rand.nextInt (j) + i;
if(!(i > j))
{
System.out.format("%4d", randomNum);
} else
{
System.out.format("%4s", "-");
}
}
System.out.println();
}
The output I need is like this,
R 4 5 6 7 8 9 10
4 4 4 5 5 4 9 8
5 - 5 5 6 5 9 8
6 - - 6 6 7 9 6
7 - - - 7 7 7 7
8 - - - - 8 9 9
9 - - - - - 9 10
10 - - - - - - 10
But the problem is I didn't get output like that. output I receive is,
R 4 5 6 7 8 9 10
4 5 7 6 8 8 10 13
5 - 5 9 8 8 10 12
6 - - 9 8 11 10 11
7 - - - 8 14 9 16
8 - - - - 14 12 11
9 - - - - - 13 18
10 - - - - - - 19
And the row value is larger than the column value, Please anyone can help me? Thanks in advance.
The problem is that you are computing the cell value as the sum of a random number between 1 and the column number plus the row number. The logic I think you want is that a given cell in the matrix can be no larger than the max of the row or column number. If so, then you need to change this line:
int randomNum = rand.nextInt(j) + i;
To this:
int randomNum = rand.nextInt((Math.max(i, j) - a) + 1) + a;