首页 > 解决方案 > 如何避免Java中的无限循环

问题描述

我怎样才能重新写这个,所以我不使用 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);}
}

标签: javawhile-loop

解决方案


因此,如果要删除 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"));

推荐阅读