我正在制作一个杂货店java程序,它列出了项目的选项,并根据用户输入将它们添加到购物车。它适用于第一个选项,但之后程序无法正常运行。我似乎无法在任何地方找到这个错误!
理想情况下,我想要问的是:
您想要添加到购物车中的内容?输入数字
(让用户输入号码)
有多少?(让用户输入号码)
您想在购物车中添加其他内容吗? (y / n)
(输入y或n)
基本上当用户输入' 1'它应该将它添加到购物车等,然后询问他们是否要添加另一个项目。然后打印"您想要添加到购物车中的内容"当我输入另一个项目编号时,它会返回到while循环的开头并打印出"想要添加到购物车中的内容"而不是像第一项那样实际添加项目。
破碎的输出图片
我还提供了代码:
do {
System.out.println("What would you like to add to your cart? Enter its corresponding number");
choose = userin.nextInt();
if(choose > 14) {
System.out.println("please choose a valid option!");
keepGoing = true;
} else if(choose == 1) {
System.out.println("how many?");
int quantity;
quantity = userin.nextInt();
cart1.addToCart(FoodItems.QUINOA, 7.00, quantity);
}
System.out.print ("\nWould you like to add anything else to your cart (y/n)? ");
keepShopping = userin.next();
if(choose ==2) {
System.out.println("What would you like to add to your cart? Enter its corresponding number");
choose = userin.nextInt();
System.out.println("how many?");
int quantity;
quantity = userin.nextInt();
cart1.addToCart(FoodItems.ORGEGG, 3.45, quantity);
}
System.out.print ("\nWould you like to add anything else to your cart (y/n)? ");
keepShopping = userin.next();
System.out.println("What would you like to add to your cart? Enter its corresponding number");
choose = userin.nextInt();
if(choose == 3) {
System.out.println("how many?");
int quantity;
quantity = userin.nextInt();
cart1.addToCart(FoodItems.CCNTW, 2.99, quantity);
System.out.print ("\nWould you like to add anything else to your cart (y/n)? ");
keepShopping = userin.next();
}
}
while (keepShopping.equals("y"));
if(keepShopping.equals("n")) {
System.out.println("\n");
Register.talking();
}
System.out.println(cart1);
keepGoing = false;
}
答案 0 :(得分:0)
代码中的问题是您没有使用 else if。因此循环将不会达到while条件,直到它执行所有if情况。
这是工作代码。我还重构了你的代码以使其变得简单。
public class Cart {
public static void main(String[] args) {
Scanner userin = new Scanner(System.in);
String keepShopping;
int quantity;
do {
System.out.println("What would you like to add to your cart? Enter its corresponding number");
int choose = userin.nextInt();
if (choose > 14) {
System.out.println("please choose a valid option!");
}
System.out.println("how many?");
quantity = userin.nextInt();
if (choose == 1) {
cart1.addToCart(FoodItems.QUINOA, 7.00, quantity);
}
else if (choose == 2) {
cart1.addToCart(FoodItems.ORGEGG, 3.00, quantity);
}
else if (choose == 3) {
cart1.addToCart(FoodItems.CCNTW, 1.00, quantity);
}
System.out.print("\nWould you like to add anything else to your cart (y/n)? ");
keepShopping = userin.next();
} while (keepShopping.equals("y"));
if (keepShopping.equals("n")) {
System.out.println("\n");
}
System.out.println("");
}
}