为了账号安全,请及时绑定邮箱和手机立即绑定

如何避免Java中的无限循环

如何避免Java中的无限循环

长风秋雁 2021-09-12 19:44:19
我怎样才能重新写这个,所以我不使用 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"));


查看完整回答
反对 回复 2021-09-12
  • 3 回答
  • 0 关注
  • 307 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信