Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

if statement - Java - If Else Logic

I'm having a difficult time understanding why the second string does not print. Even if I comment out the "third string" print line, there is no output.

public class SecretMessage {
       public static void main (String [] args) {
            int aValue=4;
            if (aValue > 0){
                if (aValue == 0)
                System.out.print("first string   ");
        }
        else 
        System.out.println("second string   ");
        System.out.println("third string   ");
        }
    }

Why doesn't the "second string" print? I thought that anything under the else block would be executed, so both second and third string should be printed.

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If we indent your code properly and write the (implicit) braces, it becomes apparent what is going on:

public class SecretMessage {
    public static void main (String[] args) {
        int aValue = 4;
        if (aValue > 0){
            if (aValue == 0) {
                System.out.print("first string");
            }
        } else /* if (avalue <= 0) */ {
            System.out.println("second string");
        }
        System.out.println("third string");
    }
}

With aValue = 4;, the outer if is entered (a > 0), but not the inner if (a == 0). Thus, the else is not entered. Thus only System.out.println("third string"); gets executed.

Some remarks on your code:

  • The inner if can never be entered. If the outer if is entered, then i is > 0 and can therefore not be == 0.
  • You use System.out.print(...) and System.out.println(...). I have a feeling that you want to use one or the other. For readability, you can also neglect the trailing blanks in those statements.
  • the array-brackets ([]) should directly follow the type, without a space (String [] args -> String[] args).

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...