0
LogCat:
02-16 21:33:30.235: E/AndroidRuntime(28464): FATAL EXCEPTION: main
02-16 21:33:30.235: E/AndroidRuntime(28464): java.lang.NumberFormatException: Invalid double: ""
02-16 21:33:30.235: E/AndroidRuntime(28464): at java.lang.StringToReal.invalidReal(StringToReal.java:63)
02-16 21:33:30.235: E/AndroidRuntime(28464): at java.lang.StringToReal.parseDouble(StringToReal.java:248)
02-16 21:33:30.235: E/AndroidRuntime(28464): at java.lang.Double.parseDouble(Double.java:295)
02-16 21:33:30.235: E/AndroidRuntime(28464): at lmf.test8.MainActivity.onClick(MainActivity.java:35)
02-16 21:33:30.235: E/AndroidRuntime(28464): at android.view.View.performClick(View.java:4212)
02-16 21:33:30.235: E/AndroidRuntime(28464): at android.view.View$PerformClick.run(View.java:17476)
XML:輸入檢查只有小數
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/text_display"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button_compute"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/button_compute" />
<EditText
android:id="@+id/edit_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal" />
</LinearLayout>
MainActivity:
public class MainActivity extends Activity implements OnClickListener {
TextView text_display;
EditText input;
Button compute;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_display = (TextView) findViewById(R.id.text_display);
input = (EditText) findViewById(R.id.edit_input);
compute = (Button) findViewById(R.id.button_compute);
compute.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
String get_input = input.getText().toString();
if (!get_input.equals("") || !get_input.equals(".")) {
Double double_input = Double.parseDouble(get_input);
if (double_input > 5) {
text_display.setText("greater than 5");
}
else {
text_display.setText("less than 5");
}
}
else {
text_display.setText("");
}
}
}
每當我離開的EditText空,或者我輸入小數時,我的應用程序崩潰。但是,當我刪除if語句中的|| !get_input.equals(".")
時,即使將edittext留空,我也沒有收到錯誤。但是當我輸入一個小數時,我收到一個錯誤。如何解決這個問題呢?