简体   繁体   中英

Integer Parsing is not working for converting binary to decimal

I'm working on an app that will calculate binary two number. I'm using two EditText for getting input. Then send the value to two strings. Then using Integer.parseInt(input, 2) for converting the number to integer for calculation. But when I use Integer.parseInt the app crashes.

XML:

                <EditText
                    android:id="@+id/edit1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:hint="Enter 1st Value"
                    android:textSize="17sp" />

                <EditText
                    android:id="@+id/edit2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:hint="Enter 1st Value"
                    android:textSize="17sp" />

Java:

EditText input1, input2;
int number1, number2, number3;
String string1, string2, string3;

    input1 = findViewById(R.id.edit1);
    input2 = findViewById(R.id.edit2);
    result = findViewById(R.id.result);

    string1 = input1.getText().toString();
    string2 = input2.getText().toString();

    number1 = Integer.parseInt(string1, 2);
    number2 = Integer.parseInt(string2, 2);

    number3 = number1 + number2;

When I use number1 = Integer.parseInt(string1, 2); & number2 = Integer.parseInt(string2, 2); app crashes.

When I remove that part, then the app doesn't crash.

I've searched various solutions but found nothing working.

Note: when I set the string to some value then Inter.parseInt doesn't cause crash.

Before number1 = Integer.parseInt(string1, 2);you should check that string1 is a valid number.

At least I would do something like:

try {
   if (string1 != null && string1.trim().equals("")) {
      number1 = Integer.parseInt(string1.trim(), 2);
   }
   // check other strings...
} catch (Exception e) {
    // do something if exception occur
}

Note: At onCreate() these value (string1, string2, string3) will be probably null or empty and they will generate an exception.

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