I noticed a problem while I was programming in Java. It has been ~6 years since I've messed with Java (I've been doing front end design and development and haven't needed to program with Java since High School). I was trying to refresh my mind and do some object oriented programming and came across an issue I haven't seen before.
I was trying to setup a school database (more specifically a simple interface), and my else statement always ran even after my if statement passed. Can anyone explain to me why the else statement would run even when the if statement passes?
else {
System.out.println("Bart, come to Principal Skinner's office immediately. You broke the system. \n");
}
I wasn't able to fix this until I changed my else statement to an else if statement (to specifically disclude those if statements).
else if(!input.equals("1") && !input.equals("2") && !input.equals("3") && !input.equals("4"))
{
System.out.println("Bart, come to Principal Skinner's office immediately. You broke the system. \n");
}
Here is what the code was:
Scanner scanner = new Scanner(System.in);
int end = 0;
while(end == 0)
{
System.out.println("Welcome to Springfield Elementary School");
System.out.println("----------------------------------------");
System.out.println("Please select from the following options");
System.out.println("1) Add Course");
System.out.println("2) Remove Course");
System.out.println("3) View All Courses");
System.out.println("4) Exit");
System.out.print("-->");
String input = scanner.nextLine();
if(input.equals("1"))
{
System.out.println("That function is currently unavailable at this time");
}
if(input.equals("2"))
{
System.out.println("That function is currently unavailable at this time");
}
if(input.equals("3"))
{
System.out.println("That function is currently unavailable at this time");
}
if(input.equals("4"))
{
end = 1;
System.out.println("Thanks for accessing the Springfield Elementary School Database. Have a nice day.");
}
else {
System.out.println("Bart, come to Principal Skinner's office immediately. You broke the system. \n");
}
}
I'm not really interested in if this works or not, but why this else if works and the else statement doesn't. This isn't for school or work, but for pure learning. From my understanding of if statements, if they passed, they should skip all other conditional statements, unless it is an else if. This would seem to contradict that.
Why is my else statement always running inside my while loop?