linuxrox
linuxrox

Reputation: 139

Android conditional Operator issue

I am in the process of making an app that outputs a number between 1 and 9000 that the user selects this number is then stored as a variable that the user can call on later.

    public void onClick(View v) {
    // TODO Auto-generated method stub
    String number = urNum.getText().toString();
    if (number >= " " && <= 9000) {

        numOut.setText("Your number is set to: " + number);
    }
}

This code: (number >= " " && <= 9000)
has errors in it stating that: The operator >= is undefined for the argument type(s) String, int
-How do I go about fixing these errors?

Help on this matter would be wonderful!

Upvotes: 0

Views: 6026

Answers (2)

Cat
Cat

Reputation: 67502

Firstly, that is not valid Java syntax. You have to specify the variable each time. Second, you can't compare a number to an empty string, you have to first convert it to an integer, then compare it to another integer.

public void onClick(View v) {
    // TODO Auto-generated method stub
    String numberString = urNum.getText().toString().trim();
    int number = Integer.valueOf(numberString);
    if (number >= 1 && number <= 9000) {
        numOut.setText("Your number is set to: " + number);
    }
}

If there is a chance the value entered is not a number, you need to handle that, too:

public void onClick(View v) {
    // TODO Auto-generated method stub
    String numberString = urNum.getText().toString();
    int number;
    try {
        number = Integer.valueOf(numberString);
    } catch (NumberFormatException nfe) {
        number = 0;
    }
    if (number >= 1 && number <= 9000) {
        numOut.setText("Your number is set to: " + number);
    }
}

NOTE: You may want to educate yourself on try/catch blocks, as well as Android EditText digit restrictions, and lastly if statements with multiple conditionals.

Upvotes: 1

AW101
AW101

Reputation: 1640

The problem is that your number is currently a string, convert it to an int, then you can do something like:

int number = Integer.valueOf(urNum.getText().toString());
if (number >= 0 && number <= 9000)

Upvotes: 0

Related Questions