Reputation: 3
I am new to android development and currently working on a simple app which, among other things, needs to generate random numbers with random operators (+, -, *, /) every time. I have a "generate" button which is supposed to give different questions every time it is pressed. I know how to generate random numbers, but I don't know how to generate the random operators so that the question is different every time. I tried using a switch statement but not successful so far (or I'm missing code in it). Can anyone help? Thanks in advance.
Here is the code i have thus far:
private void goGenerate() {
num1 = (int)(Math.random()*10) + 1;
num2 = (int)(Math.random()*10) + 1;
generate();
}
private void generate() {
StringBuilder equation = new StringBuilder();
goGenerate();
operator = (int)(Math.random() *4 ) + 1;
equation.append(num1);
if(operator == 1) {
equation.append("+");
result = num1 + num2;
}
else if(operator == 2) {
equation.append("-");
result = num1-num2;
}
else if(operator == 3) {
equation.append("*");
result = num1 * num2;
}
else if(operator == 4) {
equation.append("/");
while((num1 % num2 != 0) && (num1 < num2)) {
generate();
}
result = num1 / num2;
}
textViewOperation.setText(operator);
Upvotes: 0
Views: 1069
Reputation: 3149
Make two random routines, one for your number and one, restricted to 0-3, where you associate each of the possible numbers (0 to 3) to an operator. Then it's done. Good luck.
EDIT (this works):
int operator, num1, num2, result;
StringBuilder equation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView tv1 = (TextView) findViewById(R.id.tv1);
tv1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
generate();
tv1.setText(String.valueOf(result));
}
});
}
private Integer generate() {
equation = new StringBuilder();
num1 = (int)(Math.random()*10) + 1;
num2 = (int)(Math.random()*10) + 1;
operator = new Random().nextInt(4);
equation.append(num1);
if (operator == 1) {
equation.append("+");
result = num1 + num2;
} else if (operator == 2) {
equation.append("-");
result = num1 - num2;
} else if (operator == 3) {
equation.append("*");
result = num1 * num2;
} else if (operator == 4) {
equation.append("/");
while ((num1 % num2 != 0) && (num1 < num2)) {
generate();
}
result = num1 / num2;
}
return result;
}}
Upvotes: 1