我继续为我的输出获得0.0。我不知道我做错了什么。任何帮助将不胜感激。
前几节的用户输入正常,数字正确显示。它只是在要求我得到的总数和后续数学时得到0.0,0.0,0.0
import java.util.Scanner;
public class CoffeeShop {
public static void main(String[] args) {
//Welcome Message and name prompt
String username;
System.out.println("What is your name?");
Scanner keyboard = new Scanner(System.in);
username = keyboard.next();
System.out.println("Welcome to the Java Byte Code Coffee Shop," + username + "!");
//Menus
System.out.println("Here is our menu.");
System.out.println("1. Coffee $1.50");
System.out.println("2. Latte $3.50");
System.out.println("3. Cappuccino $3.25");
System.out.println("4. Espresso $2.00");
//What item do they want?
int product_Number;
System.out.println("Please enter the item number.");
Scanner item = new Scanner(System.in);
product_Number = item.nextInt();
System.out.println("You selected item " + product_Number);
double product;
if (product_Number == 1) {
product = 1.50;
}
if (product_Number == 2) {
product = 3.50;
}
if (product_Number == 3) {
product = 3.25;
}
if (product_Number == 4) {
product = 2.00;
} else {
product = 0.00;
}
//Quantity of item
int quantity;
System.out.println("How many would you like?");
Scanner amount = new Scanner(System.in);
quantity = amount.nextInt();
System.out.println("You want " + quantity + " of them!");
//Testing Product
double total = quantity * product;
System.out.println("Total before discount and tax is " + total);
double nuTotal;
//Discount/Tax
if (total >= 10) {
nuTotal = total - (total * .1);
} else {
nuTotal = total;
}
System.out.println("Your total with discount is " + nuTotal);
double totalTax = nuTotal * .07;
System.out.println("Your total with tax is " + totalTax);
System.out.println("Thank you " + username + "! Please stop by again!");
}
}
答案 0 :(得分:5)
您的if
声明已被删除 - 我们始终保证最后一个声明会被触发,为您提供0.0
。
您应该将它们组合在一起作为if-else if-else
语句,如下:
if (product_Number == 1) {
product = 1.50;
} else if (product_Number == 2) {
product = 3.50;
} else if (product_Number == 3) {
product = 3.25;
} else if (product_Number == 4) {
product = 2.00;
} else {
product = 0.00;
}
此外,您的总陈述也是错误的 - 您只打印tax
值,而不是total + tax
值。
*:如果您选择4,那么它实际上会起作用。但那是因为选择4附加到else
。
答案 1 :(得分:0)
你也可以这样做:
double product = 0;
if (product_Number == 1) {
product = 1.50;
}
if (product_Number == 2) {
product = 3.50;
}
if (product_Number == 3) {
product = 3.25;
}
if (product_Number == 4) {
product = 2.00;
}
将变量产品值赋予null(0),然后在代码的下方给它一个新值。