0

My Android app crashes during if statement and I can not find the mistake.

Here is a snippet of my code, how could I fix it?

    public String formatResult(String inVal) {

         String tmp = inVal.substring(inVal.length() - 2, inVal.length());

         if (tmp.equals(".0") == true){

             return inVal.substring(inVal.length(),inVal.length()-2);
         } else {

             return inVal;
         }
    }
5
  • 1
    You don't need the == true, .equals already does that for you. Commented Dec 30, 2012 at 20:36
  • 2
    whats the error message ? Commented Dec 30, 2012 at 20:37
  • To figure out crashes, always start with showing us the logs for the crash Commented Dec 30, 2012 at 20:37
  • return inVal.substring(inVal.length(),inVal.length()-2); You're going backwards in this line. Your 2nd arg is smaller than the first? Commented Dec 30, 2012 at 20:41
  • Sorry, I#m really new to IntelliJ and Java/Android. The whole app crashes. Commented Dec 30, 2012 at 20:43

3 Answers 3

1

"inVal" can be shorter than 2 characters. Debug the project and watch inVal, in any case put if-statements to control if inVal is longer than 2.

You can change:

if (tmp.equals(".0") == true)

to:

if (tmp.equals(".0")){

Another thing is, do you really want to return:

inVal.substring(inVal.length(),inVal.length()-2);

or you want to return:

inVal.substring(inVal.length()-2, inVal.length());

EndIndex cannot be smaller than StartIndex. If you want to start from end to end-2:

string a;
for(int i = inVal.length; i>=inVal.length-2; i--) {
    a += inVal.charAt(i);
}

This should work.

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

1 Comment

Hi, I want return inVal.substring(0,inVal.length()-2);. Thanks
1

inVal.substring(inVal.length(),inVal.length()-2);

not very valid since:

public String substring(int beginIndex,
                        int endIndex)

IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

Comments

0
String a = editboxa.getText().toString();
String b = editboxb.getText().toString();
if(a.equals(b))
    //do something
else
    //do something

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.