1

我正在编写一个气体计算器,它有两个输出(总气体成本和总加仑数);我怎样才能在前面加上“$”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;
        }
    }
}
4

1 回答 1

0

您应该将其预先附加到 String 变量:

totalCost.setText(output);

totalCost.setText("$"+output);
于 2012-12-05T20:07:47.690 回答