安卓如何计算百分比

3

我是一名新手,对于Android和Java都不太熟悉。我需要设计一个简单的应用程序,读取一个金额并在toast中显示这个金额的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%按钮时,应用程序关闭。我不知道我的错误在哪里,请帮忙。

请发布您的Logcat错误。 - denvercoder9
我不知道如何使用Android Studio和BlueStacks进行调试。 - user3640056
@user3640056 参考这个链接 https://developer.android.com/tools/debugging/debugging-studio.html,它会帮助你学习如何进行调试。 - Fahim
“点击10%按钮”是什么意思? - Apurva
你的代码没问题,请在点击按钮之前在编辑框中输入值。 - Sanjeet A
显示剩余2条评论
1个回答

20

您的代码很好,除了无效的双精度解析处理之外。您可以对无效的双精度解析进行修改,方法如下:

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();

        }

    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接