mercredi 17 octobre 2018

How to Print Random number in a Math Table?

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.




Aucun commentaire:

Enregistrer un commentaire