按钮导致致命异常:main,以及如何插入“$”

时间:2012-12-05 20:04:37

标签: java android

我正在编写一个有两个输出(气体总成本和总加仑)的气体计算器;如何在totalCost前面加上“$”,而不是在totalGas前面?

当我在模拟器中运行程序时,当我单击重置按钮时,它会强制关闭程序并出现FATAL EXCEPTION: main错误。

编辑:我明白了。我忘了在重置按钮上导入myClickHandler。

这是java文件:

package com.example.gas;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import com.example.gas.R;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity 
{

    private EditText totalMiles;
    private EditText price;
    private EditText mpg;
    private TextView totalGas;
    private TextView totalCost;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        totalMiles = (EditText) findViewById(R.id.milesTxt);
        totalCost = (EditText) findViewById(R.id.costTxt);
        totalGas = (EditText) findViewById(R.id.gasTxt);
        price = (EditText) findViewById(R.id.priceTxt);
        mpg = (EditText) findViewById(R.id.mpgTxt);
    }

    public void myClickHandler(View view)
    {
        NumberFormat nf = new DecimalFormat("#,###.00");
        switch (view.getId())
        {
            case R.id.calcBtn:
                float inputMiles = Float.parseFloat(totalMiles.getText().toString());
                float inputMPG = Float.parseFloat(mpg.getText().toString());
                float inputPrice = Float.parseFloat(price.getText().toString());
                float result1 = inputMiles/inputMPG;
                String output1 = nf.format(result1);
                totalGas.setText(output1);
                float result = result1 * inputPrice;
                String output = nf.format(result);
                totalCost.setText(output);
                break;

            case R.id.resetBtn:
                totalMiles.setText("");
                totalCost.setText("");
                totalGas.setText("");
                price.setText("");
                mpg.setText("");
                break;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您应该将它预先挂起到String变量:

totalCost.setText(output);

totalCost.setText("$"+output);