我是Android和Java的新手,我必须设计一个简单的应用程序来读取数量并在吐司中显示这个数量的10%。这是我的代码:
activity_main.xml中:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/amount"
android:hint="Bill amount in L.L"
android:layout_marginTop="53dp"
android:layout_below="@+id/text"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:inputType="number"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="10%"
android:id="@+id/button"
android:layout_below="@+id/amount"
android:layout_centerHorizontal="true"
android:layout_marginTop="65dp"
android:onClick="tenp"/>
MainActivity.java:
public void tenp(View view1) {
EditText e = (EditText) findViewById(R.id.amount);
double amount = Double.parseDouble(e.getText().toString());
double res = (amount / 100.0f) * 10;
Toast.makeText(getApplicationContext(), "" +res, Toast.LENGTH_SHORT).show();
}
当我运行我的应用程序并单击10%按钮时,应用程序将关闭。我不知道这里的错误是什么。请帮忙。
答案 0 :(得分:10)
您的代码很好,除了处理无效的double解析。 您可以修改代码以无效解析double as -
public void tenp(View view1) {
EditText e = (EditText) findViewById(R.id.amount);
if (!e.getText().toString().equals("")) {
double amount = Double.parseDouble(e.getText().toString());
double res = (amount / 100.0f) * 10;
Toast.makeText(getApplicationContext(), "" + res, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Amount cannot be empty", Toast.LENGTH_SHORT).show();
}
}