我该如何重新编写此代码,以便不使用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);}
}
答案 0 :(得分:2)
因此,如果要删除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"));
答案 1 :(得分:2)
我认为最简单的方法是将while循环的条件设置为与if条件相反的条件,例如:
ArrayList<Account> accounts = new ArrayList<Account>();
public void enterCustomers()
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter customer names or q to quit entering names");
System.out.println("Enter a customer name:");
Stirng name = scan.nextLine();
while(!name.equalsIgnoreCase("q"))
{
System.out.print("Enter openning balance: ");
Double balance = scan.nextDouble();
Account a = new Account(name, balance);
accounts.add(a);
System.out.print("Enter a customer name: ");
name = scan.nextLine();
}
}
答案 2 :(得分:0)
首先要注意scan.nextDouble(),因为它正在读取数字但不读取折线,因此您必须添加一个虚拟scan.nextLine()或类似的东西,以读取数字后的折线。 / p>
我总是喜欢让方法做一件事情,例如askForData(Scanner scan),所以看起来像这样:
import java.util.Scanner;
public class SomeTest {
public static void main(String[] args) {
System.out.println("Enter customer names or q to quit entering names");
Scanner scan = new Scanner(System.in);
String name="notExit"; //some name that is not exiting
while(!name.equalsIgnoreCase("q")){
name = askForData(scan);
}
}
private static String askForData(Scanner scan) {
System.out.print("Enter a customer name: ");
String name = scan.nextLine();
if (!name.equalsIgnoreCase("q")) {
System.out.print("Enter openning balance: ");
Double balance = scan.nextDouble();
scan.nextLine(); //to read the break line
}
return name;
}
}