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
语句呢
# 1 楼答案
实际上,如果条件(在括号(condition)中)的计算结果为true,则无论条件是什么,都将执行if语句。只要条件为真,就将进入if块。只要条件if为false,则不会输入if块
这就是为什么你的第一个和最后一个如果:
不会被输入,因为它们总是导致false(因此,也不会打印任何内容)
这就是说,尽管毫无用处,人们也可以直接在if语句中输入真假作为条件:
如果分别为真或假,则始终执行或不执行其块
“真”作为检查条件的实际使用通常伴随着无限循环:
但我不这么认为
有任何实际用途
# 2 楼答案
我认为你把非正式语言和计算机混淆了。在非正式语言中,“真”本身并不意味着什么——有些陈述必须是真的。例如,“1+1=2”是真的,“天空是蓝的”是真的,但我们永远不会说“真的”是真的
在计算机方面,你可以。在
if
之后,可以放置类似5 > 1
或2 == 9
的内容,但也可以只写true
或false
如果你感到困惑,你可以把
if (true)
想象成与if (0 == 0)
一样,把if (false)
想象成与if (0 == 1)
一样# 3 楼答案
true
这里有一个boolean
。这将是一样的这将只输出“first”
# 4 楼答案
在java中,可以使用嵌套的if语句或多个if语句
语法:
同时,请参阅以下参考资料,了解java中if-else的解释和示例
java中的If-else-explanation
java中的If-else-example
# 5 楼答案
您应该真正了解一般的条件语句Here's one,它谈论
IF
语句语法是
# 6 楼答案
事实上。您没有在代码中使用variables;有一个{}{a2}是{}。因此,从这个意义上讲,默认情况下为Java^{} variable 分配什么(文字)值并不重要