Reputation: 55
How can i re write this so I'm not using a while(true) loop? I need the method to break upon the conditions of the while loop and I can't seem to work it out.
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);}
}
Upvotes: 0
Views: 4661
Reputation: 723
first of all be aware of scan.nextDouble() as it is reading the number but not the breakline, you will have to add a dummy scan.nextLine() or sth similar to read the break line after the number.
I always prefer to have methods doing one thing for example askForData(Scanner scan), so It would look like that:
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;
}
}
Upvotes: 0
Reputation: 150
So if you want to remove the while(true) loop, you could use the following:
String name = scan.nextLine();
while(!name.equalsIgnoreCase("q")){
//do stuff here
name = scan.nextLine();
}
Or an even better way would be, (avoiding the duplicate name assignments,) using the do while loop, because do while would check the condition after we enter the loop:
String name;
do{
name = scan.nextLine();
//do stuff here
}while(!name.equalsIgnoreCase("q"));
Upvotes: 2
Reputation: 31
I think the easiest way to approach this is to set the condition of a while loop to the opposite of the if condition like so:
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();
}
}
Upvotes: 2