java - 如何避免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);}
}
解决方案
因此,如果要删除 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"));
推荐阅读
- google-apps-script - 您可以将电子表格导出为 PDF 的随机“限制”次数
- python - 如何在 selenium chromedriver 77.0.8.3865.40 python 中使用身份验证凭据设置代理?
- mysql - 如何在单个sql中连续连接几个表
- mongodb - 将数据从 couchbase 本地复制到 AWS documentdb
- maple - 需要一个 Maple 程序
- python-3.x - ModuleNotFoundError: No module named : xml_parser & augments
- java - Recyclerview 不显示项目?
- javascript - React Native,成功设置状态但想同时保存在 asyncStorage
- python - 带有少量变量的散点矩阵,目标在 Y 轴
- python - matplotlib如何遍历子图中的每个轴