Java 为输出获取0而不是预期的计算
我的产出一直是0.0。我不知道我做错了什么。任何帮助都将不胜感激 我的前几个部分的用户输入是正确的,并且数字显示正确。只有在求总数和后续的数学运算时,我才得到0.0,0.0,0.0Java 为输出获取0而不是预期的计算,java,Java,我的产出一直是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 use
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.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
上的,您也可以这样做:
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),然后给它一个新的值进一步向下的代码。因此,投入更多的调试输出,并准确跟踪哪一行“丢失”您的值…请发布高质量的代码-这个缩进伤害眼睛@基蒂普尔:修正了压痕。使用IntelliJ或任何自动格式化IDE真的不难,那么花两分钟做这件事有什么害处呢?你知道,如果能在其功能中添加简单的文本缩进,那就太好了。这是一段有点难看的代码,但并不比简单的control-K缩进4操作糟糕多少。@Makoto如果它很简单,请在这里发布代码之前执行它。你在寻求帮助,而不是我。此时,你正在检查每一个可能的块,无论是否设置了值。比if-else-if-else甚至开关更不理想。