0

I'm having an issue sorting my random number array.

What I'd like to do is make an if statement to make sure arr[0] is always greater than arr[1].

Why? Well, my program generates two random numbers from 0 - 99, and it does simple math problems such as subtraction and division. Since you can't divide 55 / 99 properly, the first arr[0] should always be larger than arr[1].

Here's where I'm at and thanks for your help!

public static int[] randomNumbers(){
    Random obj = new Random();

    int arr[] = new int[2];   //init array to hold 2 numbers

    arr[0] = obj.nextInt(99); //number 1 randomized 0 - 9 // sort array
    arr[1] = obj.nextInt(99); //number 2 randomized 0 - 9

    //do compare to make sure arr[0] is always greater than arr[1]
    //but how???

    return arr;

    /*int rgen = obj.nextInt(10); //first number has to be larger than second 0 - 10
    int rgen1 = obj.nextInt(9); //random 0 - 9
    int randomNumber = rgen + rgen1; //stores the answer*/
}
3
  • 2
    if(arr[0] < arr[1]) ? Commented Apr 7, 2014 at 20:34
  • 1
    You know that those numbers are in the range 0 to 98, right? Commented Apr 7, 2014 at 20:46
  • Sometimes I forget... ;) Commented Apr 7, 2014 at 20:49

2 Answers 2

4

Just generate two numbers, and then switch them if the second is larger.

if (arr[1] > arr[0]) {
    int temp = arr[0];
    arr[0] = arr[1];
    arr[1] = temp;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You are generating number from 0 to 98. If you want to include 99 you should call obj.nextInt(100).

arr[0] = obj.nextInt(100);
if(arr[0]==0)
   arr[1]=0;
else
   arr[1] = obj.nextInt(arr[0]+1);

arr[0] will get a number in [0,100[

If the generated number is 0, arr[1] can be only 0.

Else, arr[1] will get a number in [ 0,arr[0]+1 [ (so [ 0,arr[0] ]);

Note : Passing non-positive number to nextInt() will raise an exception.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.