0

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?

4
  • 1
    From my understanding of if statements, if they passed, they should skip all other conditional statements What? No. They skip the else branch, everything else is executed. Commented Jul 11, 2019 at 22:02
  • 5
    Each if is a separate statement. Your else is attached to the statement if (input.equals("4")).... So it will run for any input that is not equal to "4". Commented Jul 11, 2019 at 22:03
  • 1
    You'd be better off using a switch Commented Jul 11, 2019 at 22:05
  • You could also use the loop keyword continue to escape the current while iteration after each println. (Or use break to escape from the entire while loop) Commented Jul 11, 2019 at 22:12

2 Answers 2

3

If statements are very simple, and the problem you ran into was very simple as well. When you do

if(cond1){
    code1
}

if(cond2){
    code2
}else{
    code3
}

It evalutes, if cond1 is true, then run cond 1. Then it does: if cond2 is true, run code2, otherwise (else) run code3.

You had all your if statements separate so the only one the else applied to was the last one. What you were looking for was an else-if.

e.g.

if(cond1){
    code1
}else if(cond2){
    code2
}else{
    code3
}

This will only run that last else statement if all of your if statements evaluate to false.

Alternatively you can use a switch statement, these can be more confusing and sometimes more powerful, so I'll just link to it and let you read about it. https://www.w3schools.com/java/java_switch.asp

Sign up to request clarification or add additional context in comments.

5 Comments

Okay, I think I understand. Like I said, it has been many years since I've messed with Java. Thanks for the prompt reply. It looks like I have a lot to relearn.
This is stuff that you end up doing so much that eventually you won't even notice, you'll just do it. Good luck!
Would I be able to use a switch statment with Strings? The reason why I set it up with if statements was because I wanted to protect against anyone entering anything into the system.
Yes, it'll try to exactly match it. Also if you want to stop anyone from inputting things that could harm your program, you'll have to sanitize the input.
FWIW, the original problem isn't specific to Java. It's how every programming language with an if-then-else structure works.
1

else is only applicable to the last if statement(the one checking for "4"), if you don't want to check other conditions once one is true, either use switch or add continue; inside if. i.e.:

if(input.equals("1")) {
  System.out.println("That function is currently unavailable at this time");  
  continue;
}
if(input.equals("2")) {
  System.out.println("That function is currently unavailable at this time");  
  continue;
}
...

switch example:

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();
      switch(input) {
        case "1":
        case "2":
        case "3":
           System.out.println("That function is currently unavailable at this time");
           break;
        case "4":
           end = 1;
           System.out.println("Thanks for accessing the Springfield Elementary School Database. Have a nice day.");
           break;
        deafult:
           System.out.println("Bart, come to Principal Skinner's office immediately. You broke the system. \n");
      }
    }

1 Comment

Okay, this makes much more sense to me now. Essentially, I want to group all the conditional statements together when I run an else statement, either by using else if and else, or by using switches, right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.