1

当我尝试将编辑文本值分配为浮动时,我的应用程序强制关闭。这是代码。我还尝试了 Float.parseFloat() 方法而不是 Float.valueOf()。如果我取消我的 getETvalue() 方法,那么应用程序就可以工作。请帮忙

package com.example.aviator_18;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.Menu;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    float Remaining,Departure,TotUplift,SG,DiscResult;
    int CalUpliftResult;
    TextView RemainingTV,DepartureTV,UpliftTV,SGtv,CalcUpliftTV,DiscrepancyTV;
    EditText RemainingET,DepartureET,TotUpliftET,SGet,CalcUpliftET,DiscrepancyET;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setupView();
        getETvalue();
        evaluation();
        CalcUpliftTV.setText(String.valueOf(CalUpliftResult));
        DiscrepancyTV.setText(String.valueOf(DiscResult));


    }

    private void getETvalue() {
        String a,b,c,d,e;
        Remaining=Float.valueOf(RemainingET.getText().toString());
        Departure=Float.valueOf(DepartureET.getText().toString());
        TotUplift=Float.valueOf(TotUpliftET.getText().toString());
        SG=Float.valueOf(SGet.getText().toString());



    }

    private void evaluation() {


        CalUpliftResult=Math.round(TotUplift*SG);
        DiscResult=((Departure-Remaining-CalUpliftResult)/CalUpliftResult)*100;

    }

    private void setupView() {
        RemainingET=(EditText)findViewById(R.id.remainingET);
        DepartureET=(EditText)findViewById(R.id.departureET);
        TotUpliftET=(EditText)findViewById(R.id.TotalUpliftET);
        SGet=(EditText)findViewById(R.id.SGet);

        CalcUpliftTV=(TextView)findViewById(R.id.CalUpliftResult);
        DiscrepancyTV=(TextView)findViewById(R.id.discResult);



    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}
4

2 回答 2

0

Float.valueOf将转换包含字符串形式的浮点数的字符串值。但是如果字符串包含任何不能解析成浮点数的东西,那么这个方法会抛出NumberFormatException

像:

float f = Float.valueOf("12.35") //this is correct

尽管

float f = Float.valueOf("abcd") //this is incorrect

这会导致力关闭,因为它必须投掷NumberFormatException

来自 javadocs

的价值

public static Float valueOf(String s)
                     throws NumberFormatException
Returns a Float object holding the float value represented by the argument string s.

Throws:
NumberFormatException - if the string does not contain a parsable number.
于 2013-02-17T12:24:16.363 回答
0

您需要确保可以将字符串解析为浮点数。您可以添加 try - catch

try {
   Remaining=Float.parseFloat(RemainingET.getText().toString());
} catch (NumberFormatException nfe) {
    // Handle exception
}
于 2013-02-17T12:28:40.440 回答