Tjack12
Tjack12

Reputation: 23

Code not reaching if statement

I have the following code:

public void click(View v)
{
    Button b = (Button) v;
    TextView viewEditText = (TextView) findViewById(R.id.functionTextView);
    String editText = viewEditText.getText().toString();

    if (b.getId() == R.id.backspace)
    {
        if (viewEditText.length() > 0)
        {
            if (editText.substring(editText.length() - 1, editText.length()) == ".")
            {
                periodTrue = false;
            }
            viewEditText.setText(viewEditText.getText().toString().substring(0, viewEditText.length() - 1));
        }
    }
}

In this code I check to see if the character being backspaced is a period, if the previous condition is true. It sets the variable periodTrue to false. This tells the app that another period can be added.

Everything works with the backspace key as normal, except it never makes it inside the if statement where the variable is set. It throws no errors and I have checked with

viewEditText.append(editText.subString(editText.length()-1, editText.length()); to verify that the returned character is ".".

I don't know why it's not working, and it throws no errors or warnings either, on compile or run time. So I've come to you to see if a different perspective can show what I'm obviously doing wrong.

Upvotes: 2

Views: 229

Answers (1)

Cat
Cat

Reputation: 67502

if (editText.substring(editText.length() - 1, editText.length()) == ".")

This won't work as you're comparing the references of the two Strings, which will be different. (More in-depth explanation in this question: How do I compare strings in Java?)

Use the following instead:

if (".".equals(editText.substring(editText.length() - 1, editText.length())))

Upvotes: 2

Related Questions