Chris - 1 year ago 72
Java Question

Only positive sums - Random sum generator [JAVA]

I'm trying to create a random sum generator that generators random sums!

The only problem with what I created is, it can generate sums that have a negative result as well. So I want it to only generate sums with positive outcomes.

Example:

``````7-10 = -3
``````

My code:

``````number1 = (int)(Math.random()* LT) + 1;
number2 = (int)(Math.random()* LT) + 1;
operator = (int)(Math.random()* OP) + 1;

switch(operator) {
case 1:
operation = "+";
result = number1 + number2;
break;
case 2:
operation = "-";
result = number1 - number2;
break;
case 3:
operation = "*";
result = number1 * number2;
break;
case 4:
operation = "/";
result = number1 * number2;
break;
}
``````

Since you will always be dealing with positive integers your only issue is checking for negative numbers in your subtraction case. I would also recommend switching to the `Random` class to generate random integers. One way to get around negative results is to flip the numbers you are subtracting.

``````boolean flip = false;
int num1, num2, op, result;
String operation;
Random r = new Random();

num1 = r.nextInt(8)+2;
num2 = r.nextInt(8)+2;
op = r.nextInt(4);

switch(op) {
case 0:
// Always be positive.
operation = "+";
result = num1+num2
break;
case 1:
// Could be negative if num2 is larger than num1. Simply flip the numbers.
flip = num1 < num2;
operation = "-";
result = flip ? num2-num1 : num1-num2;
break;
case 2:
// Always be positive.
operation = "*";
result = num1*num2;
break;
case 3:
// Always be positive.
operation = "/";
result = num1/num2;
break;
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download