java 这段代码有什么问题?我正在尝试做一个程序,计算税收和小费,并遇到了这个问题

c9x0cxw0  于 2023-04-28  发布在  Java
关注(0)|答案(3)|浏览(144)

我觉得我错过了某种形式的转变。我对Java还是新手,所以对它了解不多。请帮帮我

public static void main(String[] args){
    String mealCharge;
    double tax;
    double tip;
    double total;
    

    tax = mealCharge * 0.0625; //food tax is 6.25%
    tip = mealCharge * 0.15; //tip is 15%
    total = mealCharge + tax + tip;

    mealCharge = JOptionPane.showInputDialog("Please enter the charge for the meal.");
    JOptionPane.showMessageDialog(null, "Your total will be $" + total ".");

    
}

}

jutyujz0

jutyujz01#

在代码中,mealChargeString数据类型。但是你不能在计算中使用String类型。您需要将mealCharge转换为double/int/float/large/short数据类型。我想,你需要一个双重类型。
因此,我为用户输入创建了一个新变量String mealChargeInput和新变量double mealCharge;。然后使用Integer.parseInt()方法将string转换为double。
代码如下:

public static void main(String[] args) {
    String mealChargeInput; //Create a different name for "mealCharge" string
    double mealCharge;
    double tax;
    double tip;
    double total;

    mealChargeInput = JOptionPane.showInputDialog("Please enter the charge for the meal.");
    System.out.println(mealChargeInput.getClass().getSimpleName());
    mealCharge =  Double.parseDouble(mealChargeInput); // Convert string value of "mealChargeInput" to the double value and assign it to a new double variable

    tax = mealCharge * 0.0625; //food tax is 6.25%
    tip = mealCharge * 0.15; //tip is 15%
    total = mealCharge + tax + tip;

    JOptionPane.showMessageDialog(null, "Your total will be $" + total +"."); //Missing "+" operator;

}

这是你需要的吗

oyxsuwqo

oyxsuwqo2#

你不能将一个字符串(即mealCharge)乘以Double(即tip/tax)。将mealCharge的数据类型更改为Double,就可以开始了。

1yjd4xko

1yjd4xko3#

从你的代码来看,我相信你没有用值初始化它。这将导致错误,因为在尝试计算之前没有值。

public static void main(String[] args){
double mealCharge;
double tax;
double tip;
double total;

mealCharge = Double.parseDouble(JOptionPane.showInputDialog("Please enter the charge for the meal."));

tax = mealCharge * 0.0625; //food tax is 6.25%
tip = mealCharge * 0.15; //tip is 15%
total = mealCharge + tax + tip;

JOptionPane.showMessageDialog(null, "Your total will be $" + total + ".");

}

相关问题