【问题标题】:Integer Parsing is not working for converting binary to decimal整数解析不适用于将二进制转换为十进制
【发布时间】:2020-04-25 04:37:34
【问题描述】:

我正在开发一个可以计算二进制两个数的应用程序。我正在使用两个EditText 来获取输入。然后将值发送到两个字符串。然后使用Integer.parseInt(input, 2) 将数字转换为整数进行计算。但是当我使用 Integer.parseInt 时,应用程序崩溃了。

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;

当我使用 number1 = Integer.parseInt(string1, 2);number2 = Integer.parseInt(string2, 2); 时,应用程序崩溃。

当我删除该部分时,应用程序不会崩溃。

我已经搜索了各种解决方案,但没有发现任何工作。

注意:当我将字符串设置为某个值时,Inter.parseInt 不会导致崩溃。

【问题讨论】:

  • 你能找到堆栈跟踪吗?
  • 您需要捕获任何潜在的数字格式异常。如果将其设置为值时它没有崩溃,那么它可以工作,您只需要处理字符串为空或不是数字的情况
  • 那么R.id.edit1R.id.edit2的内容是什么?如果它是有效的二进制数,它是否有效?
  • 提交@dan1st
  • @Tyler,我该怎么做?

标签: java android string binary


【解决方案1】:

之前 number1 = Integer.parseInt(string1, 2); 你应该检查 string1 是一个有效的数字。

至少我会做这样的事情:

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

注意: 在 onCreate() 中,这些值(string1、string2、string3)可能为 null 或为空,它们将生成异常。

【讨论】:

  • 您在测试时修剪string1,但在解析时不修剪。你确定吗?
  • @dan1st:操作,我忘记了。我现在已经编辑了答案
  • 这有帮助。我使用 input length != 0 语句然后解析整数。
猜你喜欢
  • 2014-03-13
  • 1970-01-01
  • 2010-12-08
  • 1970-01-01
  • 2012-06-26
  • 2011-01-08
  • 1970-01-01
  • 2014-04-16
  • 2021-11-29
相关资源
最近更新 更多