【发布时间】:2019-01-19 19:02:23
【问题描述】:
基本上我是在 blueJ 中制作一个购物应用程序,但我偶然发现了一个问题。我已经制作了 if 语句,允许用户 1. 购物 2. 检查购物篮 3. 去结账,当我输入 1 进行购物并将我的东西添加到购物清单时,我似乎无法退出内循环。关于如何解决此问题的任何想法?
import java.util.Scanner;
import java.util.ArrayList;
public class List
{
public String itemsList;
ArrayList<String> alist=new ArrayList<String>();
public List()
{
}
/*public String itemList()
{
System.out.println("1. Veg");
System.out.println("2. sweets");
System.out.println("3. drink");
System.out.println("4. toiletries");
return itemsList;
}
*/
public void Shopping()
{
Scanner sc = new Scanner(System.in);
System.out.println("1. do shopping");
System.out.println("2. check basket");
System.out.println("3. go to checkout");
String choice1 = sc.next();
if(choice1.equals("1"))
{
boolean stop = false;
while(!stop){
Scanner scanner = new Scanner(System.in);
System.out.println("1. Veg");
System.out.println("2. sweets");
System.out.println("3. drink");
System.out.println("4. toiletries");
System.out.println("5. alcohol");
System.out.println("6. go back");
String choice = scanner.next();
if(choice.equals("1"))
{
System.out.println("Veg has been added to your basket");
alist.add("veg");
}else if(choice.equals("2"))
{
System.out.println("sweets have been added to your basket");
alist.add("veg");
}else if(choice.equals("3"))
{
System.out.println("drinks have been added to your basket");
alist.add("veg");
}else if(choice.equals("4"))
{
System.out.println("toiletries have been added to your basket");
alist.add("veg");
}else if(choice.equals("5"))
{
Scanner scanner1 = new Scanner(System.in);
System.out.println("Check ID if age is under 25");
System.out.println("How old are you?");
int underAge = scanner1.nextInt();
int i;
i = 18;
if(underAge < i)
{
System.out.println("You are not old enough to buy alcohol");
} else{
System.out.println("Alcohol has been added to your basket");
alist.add("veg");
}
}else if(choice.equals("6"))
{
}
}
}else if(choice1.equals("2")){
System.out.println(alist);
}else if(choice1.equals("3")){
System.out.println("Are you sure you want to checkout? ");
System.out.println("1. No");
System.out.println("2. Yes");
Scanner scanner3 = new Scanner(System.in);
String checkout = scanner3.next();
if(checkout.equals("1"))
{
return;
} else {
System.out.println("test");
}
}
}
}
【问题讨论】:
-
也许是
break;声明?将stop设置为true? -
不要在循环中创建新的扫描仪。重用
sc而不是scanner(和scanner1和scanner3等)。 -
请使用
switch-case。而你每次都做alist.add("veg");,这显然是错误的 -
@GBlodgett 当我添加休息时;它只是阻止我完全使用该程序?
-
不,请阅读
break- 它会停止像while和for这样的循环