Reputation: 1
Hello I'm trying to make an app that gives you 2 random numbers and the user has to add the 2 random numbers, so my error is that that the random numbers are widgets not integers,
I have tried hundreds of explinations but nothing is working.
public void action(View v){
num1.setText(String.valueOf(randNum1.nextInt(10)));
num2.setText(String.valueOf(randNum2.nextInt(10)));
userAnswer.getText();
if (num1 + num2){
}
}
and this is the error:
bad operand types for binary operator '+' first type: TextView second type: TextView
Upvotes: 0
Views: 94
Reputation: 537
You can follow the below steps. i assume randNum1 and randNum2 is random number and num1 and num2 is TextView.
public void action(View v){
num1.setText(String.valueOf(randNum1.nextInt(10)));
num2.setText(String.valueOf(randNum2.nextInt(10)));
userAnswer.getText();
int randNumber1 = Integer.parseInt(num1.getText().toString());
int randNumber2 = Integer.parseInt(num2.getText().toString());
if (randNumber1 + randNumber2 ){
//your logic write here
}else{}
}
Upvotes: 0
Reputation: 6460
The problem you have is well described by the error you are receiving.
From the code snippet you have provided, I am guessing num1 and num2 are references to textview objects.
You CANNOT perform addition on the textview objects themselves, but rather on their content.
So, what you are trying to achieve is this:
public void action(View v){
num1.setText(String.valueOf(randNum1.nextInt(10)));
num2.setText(String.valueOf(randNum2.nextInt(10)));
userAnswer.getText();
String num1String = num1.getText().toString();
String num2String = num2.getText().toString();
int firstNumber = Integer.parseInt(num1String);
int secondNumber = Integer.parseInt(num2String);
if (firstNumber + secondNumber){
// YOUR LOGIC
}
}
Or better yet, you could save the generated random numbers to variables and use them later, like so:
public void action(View v){
int randomNumberOne = randNum1.nextInt(10);
int randomNumberTwo = randNum2.nextInt(10);
num1.setText(String.valueOf(randomNumberOne));
num2.setText(String.valueOf(randomNumberTwo));
userAnswer.getText();
if (randomNumberOne + randomNumberTwo){
// YOUR LOGIC
}
}
Upvotes: 1