有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JAVA中的If语句给出错误

代码如下:

public class Demo
{
    public static void main(String[]args)
    {
       if(5>10)                                        
          System.out.println("5>10");
       if(true)         
          System.out.println("true");
       if((3+6)==(3-6))           
          System.out.println("false");
    }
}

输出为string:true(已处理第二条if语句)

我不明白为什么if(true) System.out.println("true");会被处理并打印为true。if语句中的条件true不涉及任何地方。我从课本上得到这个代码。Java中boolean的默认值应该是false,那么为什么可以打印第二个if语句呢


共 (6) 个答案

  1. # 1 楼答案

    实际上,如果条件(在括号(condition)中)的计算结果为true,则无论条件是什么,都将执行if语句。只要条件为真,就将进入if块。只要条件if为false,则不会输入if块

    这就是为什么你的第一个和最后一个如果:

    if(5>10) //false
    if((3+6)==(3-6)) //false
    

    不会被输入,因为它们总是导致false(因此,也不会打印任何内容)

    这就是说,尽管毫无用处,人们也可以直接在if语句中输入真假作为条件:

    if(true)
    

    如果分别为真或假,则始终执行或不执行其块

    “真”作为检查条件的实际使用通常伴随着无限循环:

    while(true){
      //do something infinitely till break or error
    }
    

    但我不这么认为

     if(true)
    

    有任何实际用途

  2. # 2 楼答案

    我认为你把非正式语言和计算机混淆了。在非正式语言中,“真”本身并不意味着什么——有些陈述必须是真的。例如,“1+1=2”是真的,“天空是蓝的”是真的,但我们永远不会说“真的”是真的

    在计算机方面,你可以。在if之后,可以放置类似5 > 12 == 9的内容,但也可以只写truefalse

    如果你感到困惑,你可以把if (true)想象成与if (0 == 0)一样,把if (false)想象成与if (0 == 1)一样

  3. # 3 楼答案

    true这里有一个boolean。这将是一样的

    boolean first = true;
    boolean second = false;
    if (first) {
        System.out.println("first");
    }
    if (second) {
        System.out.println("second");
    }
    

    这将只输出“first”

  4. # 4 楼答案

    在java中,可以使用嵌套的if语句或多个if语句

    语法:

    if(condition1)
    {
       // Statement1;
    
       if(condition2)
       {
          // Statement2;
       }
    }
    

    同时,请参阅以下参考资料,了解java中if-else的解释和示例

    java中的If-else-explanation

    java中的If-else-example

  5. # 5 楼答案

    I don't understand why if(true) System.out.println("true"); will be processed and print out true.

    您应该真正了解一般的条件语句Here's one,它谈论IF语句

    语法是

    if(Boolean_expression){
       //Executes when the Boolean expression is true
    }else{
       //Executes when the Boolean expression is false
    }
    
  6. # 6 楼答案

    I don't understand why if(true) System.out.println("true"); will be processed and print out true. The condition(true) in the if statement refer to nowhere. I get this code from my textbook. The default value of boolean in Java should be false, then why the second if statement can be printed out?

    事实上。您没有在代码中使用variables;有一个{}{a2}是{}。因此,从这个意义上讲,默认情况下为Java^{} variable分配什么(文字)值并不重要