即使输入有效,我也会得到 "Invalid" 结果,有人知道为什么吗?
I get "Invalid" result even with valid input, anyone know why?
当输入无效时(空,.等,crashes.Any思路?
我已经尝试了多种方法来重新排列代码,但我无法让它工作。
引入有效输入后,应用程序运行正常
public class fourth extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fourth);
final Button calc = (Button) findViewById(R.id.calculeaza);
final EditText e1 = (EditText) findViewById(R.id.inaltime);
final EditText e2 = (EditText) findViewById(R.id.greutate);
final TextView t1 = (TextView) findViewById(R.id.rezultat);
calc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String text = e1.getText().toString();
String text2 = e2.getText().toString();
if (text == ( "," ) || text == ( "" ) || text == ( "-" ) || text2 == ( "," ) || text2 == ( "" ) || text2 == ( "-" ))
{
float num1 = Float.parseFloat(e1.getText().toString());
float num2 = Float.parseFloat(e2.getText().toString());
float sum = ( num2 / ( ( num1 * num1 ) / 10000 ) );
t1.setText(Float.toString(sum));
} else {
t1.setText("Invalid");
}
}
});
}
}
首先。你的字符串比较是错误的。你应该使用 String#equals
因此:
if (text.equals(",") || text.equals("") || text.equals("-") || text2.equals(",") || text2.equals("") || text2.equals("-"))
您没有指定您收到的错误。但是我的猜测是错误发生在您将文本解析为浮点数的行上。如果 text
是 ,
.
,那么这样做是没有意义的
当输入无效时(空,.等,crashes.Any思路?
我已经尝试了多种方法来重新排列代码,但我无法让它工作。 引入有效输入后,应用程序运行正常
public class fourth extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fourth);
final Button calc = (Button) findViewById(R.id.calculeaza);
final EditText e1 = (EditText) findViewById(R.id.inaltime);
final EditText e2 = (EditText) findViewById(R.id.greutate);
final TextView t1 = (TextView) findViewById(R.id.rezultat);
calc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String text = e1.getText().toString();
String text2 = e2.getText().toString();
if (text == ( "," ) || text == ( "" ) || text == ( "-" ) || text2 == ( "," ) || text2 == ( "" ) || text2 == ( "-" ))
{
float num1 = Float.parseFloat(e1.getText().toString());
float num2 = Float.parseFloat(e2.getText().toString());
float sum = ( num2 / ( ( num1 * num1 ) / 10000 ) );
t1.setText(Float.toString(sum));
} else {
t1.setText("Invalid");
}
}
});
}
}
首先。你的字符串比较是错误的。你应该使用 String#equals
因此:
if (text.equals(",") || text.equals("") || text.equals("-") || text2.equals(",") || text2.equals("") || text2.equals("-"))
您没有指定您收到的错误。但是我的猜测是错误发生在您将文本解析为浮点数的行上。如果 text
是 ,
.