简体   繁体   中英

Why my .isEmpty does not work in this code?

I want to program a check if the user writes down a number to check before pushing the button.

public class MainActivity extends AppCompatActivity {
    int randomNumber;

    public void makeToast(String string) {
        Toast.makeText(MainActivity.this, string, Toast.LENGTH_LONG).show();
    }

    public void guess (View view) {
        final EditText showNumber = findViewById(R.id.showNumberEditText);

        int guessInt = Integer.parseInt(showNumber.getText().toString());

        if (showNumber.getText().toString().isEmpty()) {
            makeToast("Pleas Enter a Number!");
        } else if(guessInt > randomNumber) {
            makeToast("Lower");
        } else if (guessInt < randomNumber) {
            makeToast("Higher");
        } else {
            makeToast("Correct! Try Again!");

            Random random = new Random();
            randomNumber = random.nextInt(20) + 1;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Random random = new Random();
        randomNumber = random.nextInt(20) + 1;
    }
}

You must consider that the EditText may not have any value set yet, so in essence may contain Null and therefore the .toString().isEmpty() could fail with a NullPointerException . In addition if it has a the text, you need also to consider that it may not even be a number, so it needs to be converted into an integer. And strings can't be compared directly against integers, therefore needing such integer conversion is imperative.

Try the next code:

public void guess (View view) {
final EditText showNumber = findViewById(R.id.showNumberEditText);

Integer guessInt = convertToInteger(showNumber.getText());

if (guessInt == null) {
    makeToast("Pleas Enter a Number!");
 }else if(guessInt > randomNumber) {
        makeToast("Lower");
    } else if (guessInt < randomNumber) {
        makeToast("Higher");
    } else {
        makeToast("Correct! Try Again!");
        Random random = new Random();
        randomNumber = random.nextInt(20) + 1;
    }
}

public static Integer convertToInteger(final Editable source) {
    if (source != null) {
        try {
            final String text = source.toString();
            return Integer.parseInt(text);
        }
        catch (NumberFormatException ex) {
            ex.printStackTrace();
        }
    }

    return null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM