gpt4 book ai didi

java - Java:放入十进制数字时会崩溃[RESOLVE]

转载 作者:行者123 更新时间:2023-12-03 17:45:16 26 4
gpt4 key购买 nike

好的,我的问题是:我创建了一个应用程序来计算我的IMC(法语)。但是,当我尝试在EditText中以十进制输入我的身高或体重时,会返回此错误:

03-27 18:52:25.459 31274-31274/fr.imc.oxyz0n359.imc E/AndroidRuntime: FATAL EXCEPTION: main
Process: fr.imc.oxyz0n359.imc, PID: 31274
java.lang.NumberFormatException: For input string: "1.5"
at java.lang.Integer.parseInt(Integer.java:521)
at java.lang.Integer.parseInt(Integer.java:556)
at fr.imc.oxyz0n359.imc.MainActivity$1.onClick(MainActivity.java:27)
at android.view.View.performClick(View.java:5675)
at android.view.View$PerformClick.run(View.java:22641)
at android.os.Handler.handleCallback(Handler.java:836)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)

这是我的代码:
public class MainActivity extends AppCompatActivity {

private TextView Resultat;
private Button Calcul;
private EditText Poids, Taille;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resultat = (TextView)findViewById(R.id.Resultat);
Calcul = (Button)findViewById(R.id.Calcul);
Poids = (EditText)findViewById(R.id.Poids);
Taille = (EditText)findViewById(R.id.Taille);
Calcul.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int Etape = Integer.parseInt(Taille.getText().toString())*Integer.parseInt(Taille.getText().toString());
int Result = Integer.parseInt(Poids.getText().toString())/Etape;
Resultat.setText("IMC : " + Result);
}
});
}
}

感谢您的回答,OxYz0n359。

编辑:我解决了这个问题,感谢您的回答,我将代码更改为:
public class MainActivity extends AppCompatActivity {

private TextView Resultat;
private Button Calcul;
private EditText Poids, Taille;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resultat = (TextView)findViewById(R.id.Resultat);
Calcul = (Button)findViewById(R.id.Calcul);
Poids = (EditText)findViewById(R.id.Poids);
Taille = (EditText)findViewById(R.id.Taille);
Calcul.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
double etape = Double.parseDouble(Taille.getText().toString())*Double.parseDouble(Taille.getText().toString());
double result = Double.parseDouble(Poids.getText().toString())/etape;
Resultat.setText("IMC : " + result);
}
});
}
}

最佳答案

“1.5”不是整数,您需要将其解析为Double,只有在将其转换为最适合您的整数之后,才可以将其解析为Double。另外,在Java变量名称中,从小写字母开始,我建议您紧跟该习惯。

关于java - Java:放入十进制数字时会崩溃[RESOLVE],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49518480/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com