1

This is a OnClickListener for button

name is EditText

I want it print only "hi" if nothing is entered, but "hi" + name + "!" if user inputs his/her name.

public void onClick(View view) {

    if (button==view) {
        String message;

        if (name.getText().toString().matches("")) {
            message = "hi!";
            return;
        }
       else {
            message = "hi" + name.getText().toString() + "!";
            return;
        }

        Toast toast = Toast.makeText(this,message,Toast.LENGTH_SHORT);
        toast.show();
        display.setText(message);
    }
}

For some reason I got error "unreachable statement" for the line:

Toast toast =...,

And if I compile and run it, the screen will output on 2 lines instead of one, such as:

Hi

!

What did I do wrong in here?

1
  • 1
    Just remove the return. Commented Feb 28, 2016 at 23:23

1 Answer 1

1

Why do you have the return statement? You need to show the Toast and then return. Remove the return statements.

Sign up to request clarification or add additional context in comments.

5 Comments

Edit: thanks for the help! :) I was googling and searching this site before posting, somehow I thought the return is needed.
Why are you using matches? Why not simply, name.getText().toString().equals("") or better TextUtils.isEmpty(name.getText().toString())?
erm... what do you mean "simple"? I used matches because I found it while googling and searching for solution.
I have been trying those also, especially the isEmpy(). however I am running android emulator on my AMD CPU... Whenever I refresh and re-rerun my code, it's not updated immediately (5 to 15 mins long). It gives me "false error" and I thought my code doesn't work. That's why I didn't use it because I thought it didn't work. Anyway, thanks :)
matches() is a more powerful method used to match regular expression. isEmpty is a simpler method that matches only empty or null strings. If you don't need the power of regular expressions, it maybe possible to use a simpler method like isEmpty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.