我怎样才能重新写这个,所以我不使用 while(true) 循环?我需要打破 while 循环条件的方法,但我似乎无法解决。ArrayList<Account> accounts = new ArrayList<Account>();public void enterCustomers(){ System.out.println("Enter customer names or q to quit entering names"); while(true) { Scanner scan = new Scanner(System.in); //find alternative to while true System.out.print("Enter a customer name: "); String name = scan.nextLine(); if(name.equalsIgnoreCase("q")) { break; } System.out.print("Enter openning balance: "); Double balance = scan.nextDouble(); Account a = new Account(name, balance); accounts.add(a);}}
3 回答
慕森卡
TA贡献1806条经验 获得超8个赞
因此,如果要删除 while(true) 循环,可以使用以下命令:
String name = scan.nextLine();
while(!name.equalsIgnoreCase("q")){
//do stuff here
name = scan.nextLine();
}
或者更好的方法是,(避免重复的名称分配,)使用 do while 循环,因为 do while 会在我们进入循环后检查条件:
String name;
do{
name = scan.nextLine();
//do stuff here
}while(!name.equalsIgnoreCase("q"));
添加回答
举报
0/150
提交
取消