2

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.

Tjack12
  • 23
  • 2

1 Answers1

2
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())))
Community
  • 1
  • 1
Cat
  • 66,919
  • 24
  • 133
  • 141
  • This works like a charm. I appreciate you giving me the link to explain the different comparisons. My code now does what I would expect. Thanks :) – Tjack12 Nov 05 '12 at 11:06