Java-其他逻辑 [英] Java - If Else Logic

查看:215
本文介绍了Java-其他逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解为什么第二个字符串无法打印.即使我注释掉第三字符串"打印行,也没有输出.

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   ");
        }
    }

为什么不显示第二个字符串"?我认为else块下的所有内容都将执行,因此第二个和第三个字符串都应打印.

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.

提前谢谢!

推荐答案

如果我们正确地缩进您的代码并写出(隐式)花括号,那么显然发生了什么:

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");
    }
}

对于aValue = 4;,输入的是外部if(a > 0),而不是内部的if(a == 0).因此,不会输入else.因此,只有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:

  • 内部if不能输入.如果输入了外部if,则i> 0,因此不能为== 0.
  • 您使用System.out.print(...)System.out.println(...).我有一种感觉,您想使用其中之一.为了提高可读性,您还可以忽略这些语句中的尾随空白.
  • 数组括号([])应该直接跟随类型,没有空格(String [] args-> String[] args).
  • 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).

这篇关于Java-其他逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆