我是 android 和 Java 的新手,我必须设计一个简单的应用程序来读取金额并在 toast 中显示该金额的 10%。这是我的代码:
Activity 主.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% 按钮时,应用程序将关闭。我不知道我的错误是什么。请帮忙。
最佳答案
除了处理 double 的无效解析之外,您的代码很好。
您可以修改您的代码以对双作为无效的解析 -
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();
}
}
关于java - Android 计算百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28928902/