【问题标题】:java.lang.NumberFormatException: Invalid int: "" : Errorjava.lang.NumberFormatException:无效的int:“”:错误
【发布时间】:2016-04-29 01:59:03
【问题描述】:

我正在做一些计算,但无法将字符串解析为 int 甚至浮点数。我搜索了解决方案,我在某处读到它必须是一个空字符串,但我使用

检查了我的editText
log.v("Valuee",e1.getText().toString());

它的打印值证明字符串不为空.. 我错过了什么?

这里是 logcat

java.lang.RuntimeException: 无法启动活动 ComponentInfo{com.example.farrukh.bmi/com.example.farrukh.bmi.Main2Activity}: java.lang.NumberFormatException: Invalid int: "" 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 在 android.app.ActivityThread.access$800(ActivityThread.java:135) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper.java:136) 在 android.app.ActivityThread.main(ActivityThread.java:5017) 在 java.lang.reflect.Method.invokeNative(Native Method) 在 java.lang.reflect.Method.invoke(Method.java:515) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 在 dalvik.system.NativeStart.main(本机方法) 引起:java.lang.NumberFormatException: Invalid int: "" 在 java.lang.Integer.invalidInt(Integer.java:137) 在 java.lang.Integer.parseInt(Integer.java:358) 在 java.lang.Integer.parseInt(Integer.java:331) 在 com.example.farrukh.bmi.Main2Activity.onCreate(Main2Activity.java:31) 在 android.app.Activity.performCreate(Activity.java:5231) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 在 android.app.ActivityThread.access$800(ActivityThread.java:135) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper.java:136) 在 android.app.ActivityThread.main(ActivityThread.java:5017) 在 java.lang.reflect.Method.invokeNative(Native Method)

这里是 MainActivity.java

 public class Main2Activity extends AppCompatActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main2);

          final   Button b = (Button) findViewById(R.id.button);
          final   EditText e1 = (EditText) findViewById(R.id.editText2);
          final   TextView text = (TextView) findViewById(R.id.textView4);
          final  String height = e1.getText().toString();


          final int a = Integer.parseInt(height); //got error while parsing

     b.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {


                 //   Log.v("EditText",e1.getText().toString());

                }
            });


        }


    }

这里是 activity.xml

<Button
        android:layout_width="132dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
         android:layout_gravity="center_horizontal"
        android:text="CLICK"
        android:clickable="true"
        android:id="@+id/button"/>

<EditText
        android:layout_width="120dp"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:id="@+id/editText2"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp"
        android:gravity="center" />


    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:id="@+id/textView4"
        android:layout_gravity="center_horizontal"
        android:gravity="center"
        android:layout_marginTop="20dp"
        android:textColor="#3b9ff0" />

【问题讨论】:

  • 因为e1中没有值。首先点击做验证,然后转换为整数
  • e1 包含空白文本,因此问题
  • 你需要在onclick()中使用gettext()
  • @jipr311 OP 遇到NumberFormatException 非空指针异常问题。

标签: java android parseint


【解决方案1】:

onCreate() 运行时还没有任何价值。将getText()parseInt() 移动到您的点击侦听器中,以便在您输入内容时读取并解析该值。

【讨论】:

    【解决方案2】:

    您正在尝试将空字符串 ( "" ) 解析为数值,但 "" 不是数值。

    确保将其设置为必需,或在尝试解析之前检查是否为空。

    final int a = !height.equals("")?Integer.parseInt(height) : 0;
    

    例如。

    编辑:

    如果你添加了空格,那么它将是“”;

    height = height.trim();
    final int a = !height.equals("")?Integer.parseInt(height) : 0;
    

    应该可以解决问题。

    【讨论】:

    • 如果我添加了 2 个空格会怎样
    • 我已在答案中添加了对此的回复。
    • 这将避免崩溃,是的,但不允许 OP 实际读取输入的值,因为代码运行得太早了。
    • gettting 值必须在 onClick Its 中,因为它是在您在文本字段中输入一些值后单击按钮时触发的。并且 op 还可以添加一个检查 !TextUtils.isEmpty(string)
    • 没错,那么问题又是关于 NumberFormatException 的。
    【解决方案3】:

    将这些行放入onClick()

    final  String height = e1.getText().toString();
    final int a = Integer.parseInt(height);
    

    您在onCreate() 中获取e1 的值,而当用户单击按钮时您想要它

    还需要检查高度是否有任何值,检查Stuluske's这个答案

    【讨论】:

    • 可能是因为您没有考虑到身高可能不是数字。但是,我赞成这个答案,因为在onCreate() 期间使用getText() 是没用的。
    • @LordAnomander 哦,是的,我忘记了这一点,会更新我的答案
    • 谢谢 :) 我忘记了
    【解决方案4】:

    在做 Integer.parseInt 之前先检查一下

    final int a = (height == null || height.trim().equal("") ? 0 : Integer.parseInt(height));
    

    您还需要添加此代码以从 onclick 侦听器中的 edittext 获取高度值,因为在 OnCreate 控件中将没有任何值,除了您在 layout.xml 中设置一些默认值,因为它刚刚创建

    【讨论】:

      【解决方案5】:

      您应该在方法中获取值,这样您的应用程序就不会在您创建它们时立即尝试分配值,检查下面如何使用 kotlin 进行操作

           myresult = findViewById<TextView>(R.id.txtresult)
           val1 = findViewById<EditText>(R.id.valone)
           val2 = findViewById<EditText>(R.id.valtwo)
      

      获取字段使用方法后如下

          fun calculate() : Int {
      
              var value1 = Integer.parseInt(val1.text.toString())
              var value2 = val2.text.toString().toInt()
              var result : Int
      
              when (opType){
      
                  "+" ->{result = value1 + value2
                          return result
                       }
                  "-" ->{result = value1 - value2
                      return result
                  }
                  "*" -> {result = value1 * value2
                      return result
                  }
                  "/" -> {result = value1 / value2
                      return result
                  } else -> result = 20
      
              }
      
              return result
          }
      
           btn.setOnClickListener{
      
              println(calculate().toString())
              myresult.text = calculate().toString()
      
      
          }
      

      对于那些迁移到 kotlin 并发现相同错误的人,我希望这段代码对您有所帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-21
        相关资源
        最近更新 更多