Friday, June 20, 2014

Java Exercise Nr. 31 (Selections)

Write a program that displays a random coordinate in a rectangle. The rectangle is centered at (0, 0) with width 100 and height 200.

Solution:

public static void main(String[] args) {
   Scanner s = new Scanner(System.in);
   int x, y;

   // x must be from -50 to 50
   x = (int)(Math.random() * 101) - 50;
   // y must be from -100 to 100
   y = (int)(Math.random() * 201) - 100;

   System.out.print("(" + x + ", " + y + ")");
}

4 comments:

  1. if we want to generate from -50 to +500 both inclusive? then ?

    ReplyDelete
  2. sorry
    if we want to generate from -50 to +50 both inclusive? then ?

    ReplyDelete
  3. here minimum is -48.98 and maximum is 49.99
    if we want to generate exactly from -50 to +50 then how

    ReplyDelete
    Replies
    1. Math.random() generates an interval greater than or equal to 0 and less than 1. So we have 0 <= x < 1. Multiplied by 101 => 0 <= 101 * x < 101. Minus 50 => -50 <= x * 101 - 50 < 51, so both -50 and 50 are included in the above formula.

      Delete

Author