java Android 计算百分比
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28928902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android Calculate percentage
提问by user3640056
I'm new to android and Java, and I have to design a simple application that reads an amount and shows a 10 percent of this amount in a toast. This is my code:
我是 android 和 Java 的新手,我必须设计一个简单的应用程序,它读取一个数量并在吐司中显示这个数量的 10%。这是我的代码:
activity_main.xml:
活动_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:
主活动.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();
}
When I run my app and click on the 10% button, the app closes. I don't know what is my error here. please help.
当我运行我的应用程序并单击 10% 按钮时,应用程序关闭。我不知道我这里的错误是什么。请帮忙。
回答by Sanjeet A
Your code is fine except for the handling the invalid parsing of double. You can modify your code for the invalid parsing of 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();
}
}