sdfjbs sdfjbs - 21 days ago 6
Java Question

JAVA loop won't end with boolean

public class WeeklyCalendar
{

public static void main(String[] args) throws FileNotFoundException
{
ArrayList<String> apptList = readFromFile();
Scanner myScanner = new Scanner(System.in);

boolean quit = true;

while(quit = true)
{
System.out.println("Please type add, remove, printDay, printAll, or quit");
String action = myScanner.next();

if (action.equals("add"))
{
System.out.println("enter a date and time");
String enter1 = myScanner.next();
String enter2 = myScanner.next();

if (hasAppointmentAt(apptList, enter1, enter2) == true)
{
System.out.println("you already have an appointment at this day and time");
}
else
{
addAppointment(apptList, enter1, enter2);
}
}
else if (action.equals("remove"))
{
System.out.println("enter a date and time");
String enter1 = myScanner.next();
String enter2 = myScanner.next();

removeAppointment(apptList, enter1, enter2);
}
else if (action.equals("printDay"))
{
System.out.println("enter a week day");
String enter1 = myScanner.next();

System.out.println(appointmentsOnDay(apptList, enter1));
}
else if (action.equals("printAll"))
{
System.out.println(apptList);
}
else if (action.equals("quit"))
{
quit = false;
}
else
{
System.out.println("incorrectly typed");
}
}

}


In my
main()
I am trying to end the
while()
loop when "quit" is typed by making the
boolean quit = false
but it does not end the
while()
loop. It is recognizing the String
quit
and I am typing it correctly, but I just stay in the while loop. Looking to end the loop when "quit" is typed, thanks.

Answer

there is an error, you wrote:

while(quit = true)
{

instead of

while(quit == true)
{

that could be simplified in

while(quit)
{

The first expression, the wrong one, assign true to quit, and the value of this is true, so the reason loop never end. Some other languages, like C#, impose that the argument must be a boolean experession, preventing these errors

Comments