为什么我的应用程序在我将字符串(从 EditText)解析为 Float 时崩溃

Why my app crashes when I parse string (from EditText) to Float

为什么我无法将字符串(取自 EditText)转换为浮点数。

我正在构建一个简单的应用程序来根据无线电组选择计算(加法、减法、除法、乘法)两个数字。 但是,当我使用

提取字符串时
String temp =  editText.getText().toString();

然后尝试将其转换回 Float 以便对其执行操作

num1 = Float.parseFloat(temp);

正是这一行代码导致了一些错误,导致我的应用程序崩溃。 我试图用 try-catch 包围它以防止我的应用程序崩溃,但 String 仍然没有解析为 Float。

完成 Java 计算器应用代码

package com.example.calculator;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    RadioGroup radioGroup;
    float ans;
    EditText editText;
    TextView textView;
    float num1, num2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = findViewById(R.id.first_number);
        String temp =  editText.getText().toString();
        try{
            num1 = Float.parseFloat(temp);
        }catch(Exception e){
            Log.e("MainActivity", "onCreate: Still Not Working", e);
        }
        editText = findViewById(R.id.second_number);
        try{
            num2 = Float.parseFloat(editText.getText().toString());
        }catch(Exception e){
            Log.e("MainActivity", "onCreate: String unable to Assign.", e);
        }
        textView = findViewById(R.id.answer);
        radioGroup = (RadioGroup) findViewById(R.id.radio_group);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                caluclate(num1, num2);
                if(num2 == 0 && checkedId == R.id.div){
                    textView.setText("N.A.");
                }else{
                    textView.setText(String.valueOf(ans));
                }
            }
        });
    }


    float addition(float n1, float n2){
        return n1 + n2;
    }
    float subtraction(float n1, float n2){
        return n1 - n2;
    }
    float multiplication(float n1, float n2){
        return n1 * n2;
    }
    float division(float n1, float n2){
        return n1/n2;
    }

    void caluclate(float n1, float n2){
        switch(radioGroup.getCheckedRadioButtonId()){
            case R.id.add:
                ans = addition (n1, n2);
                break;
            case R.id.sub:
                ans = subtraction(n1, n2);
                break;
            case R.id.mul:
                ans = multiplication(n1, n2);
                break;
            case R.id.div:
                ans = division(n1, n2);
                break;
        }
    }

}

XML代码

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DFDFDF"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginRight="16dp"
        android:text="First Number"
        android:textColor="#2196F3"
        android:textSize="20sp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/first_number"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginRight="16dp"
        android:hint="Enter Here"
        android:inputType="numberDecimal|numberSigned"
        android:padding="8dp"
        android:background="@color/white"
        android:textStyle="bold" />

    <TextView

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginRight="16dp"
        android:text="Second Number"
        android:textColor="#2196F3"
        android:textSize="20sp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/second_number"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginRight="16dp"
        android:hint="Enter Here"
        android:padding="8dp"
        android:inputType="numberDecimal|numberSigned"
        android:background="@color/white"
        android:textStyle="bold" />

    <TextView

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginRight="16dp"
        android:text="Choose Operation"
        android:textColor="#2196F3"
        android:textSize="20sp"
        android:textStyle="bold" />

    <RadioGroup
        android:id="@+id/radio_group"
        android:paddingLeft="16dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <RadioButton
            android:id="@+id/add"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="8dp"
            android:text="Addition" />

        <RadioButton
            android:id="@+id/sub"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="8dp"
            android:text="Subtraction" />

        <RadioButton
            android:id="@+id/mul"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="8dp"
            android:text="Multiplication" />

        <RadioButton
            android:id="@+id/div"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="8dp"
            android:text="Division" />
    </RadioGroup>

    <TextView

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginRight="16dp"
        android:text="Answer"
        android:textColor="#2196F3"
        android:textSize="20sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/answer"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginRight="16dp"
        android:textSize="20dp"
        android:padding="8dp"
        android:inputType="number"
        android:background="@color/white"
        android:textStyle="bold" />

</LinearLayout>

我的应用程序一直在崩溃,直到我注释掉将 String 分配给 float 的那一行 然后我尝试使用 try-catch 块,但这只是防止我的应用程序崩溃

给你

您应该在运行时从 edittext 获取值,而不是在创建时 activity。

package com.example.calculator;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    RadioGroup radioGroup;
    float ans;
    EditText editText1,editText2;
    TextView textView;
    float num1, num2;

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

        //make sure that you entered value contains float,not other data type

        editText1 = findViewById(R.id.first_number); 
        editText2 = findViewById(R.id.second_number);
        
        textView = findViewById(R.id.answer);
        radioGroup = (RadioGroup) findViewById(R.id.radio_group);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                try{
                    num1 = Float.parseFloat(editText1.getText().toString()); //i'm getting value here
                }catch(Exception e){
                    Log.e("MainActivity", "onCreate: Still Not Working", e);
                }
                try{
                    num2 = Float.parseFloat(editText2.getText().toString());//i'm getting value here
                }catch(Exception e){
                    Log.e("MainActivity", "onCreate: String unable to Assign.", e);
                }

                caluclate(num1, num2);
                if(num2 == 0 && checkedId == R.id.div){
                    textView.setText("N.A.");
                }else{
                    textView.setText(String.valueOf(ans));
                }
            }
        });
    }


    float addition(float n1, float n2){
        return n1 + n2;
    }
    float subtraction(float n1, float n2){
        return n1 - n2;
    }
    float multiplication(float n1, float n2){
        return n1 * n2;
    }
    float division(float n1, float n2){
        return n1/n2;
    }

    void caluclate(float n1, float n2){
        switch(radioGroup.getCheckedRadioButtonId()){
            case R.id.add:
                ans = addition (n1, n2);
                break;
            case R.id.sub:
                ans = subtraction(n1, n2);
                break;
            case R.id.mul:
                ans = multiplication(n1, n2);
                break;
            case R.id.div:
                ans = division(n1, n2);
                break;
        }
    }

}