整数比较显示没有输出,为什么?

时间:2015-08-30 07:56:57

标签: java

 int a=10, b=5;
    if(a>b)
    {
    if(b>5)
    System.out.println("b is:"+b);
     }
   else
    System.out.println("a is:"+a");
}

此代码在运行时没有显示输出,为什么?

6 个答案:

答案 0 :(得分:6)

您的代码段注释:

int a=10, b=5;

if(a>b) // is true (10>5)
{
    if(b>5) // is false (5>5)
        System.out.println("b is:"+b);
    // no else case, so does nothing
}
else // never gets here
    System.out.println("a is:"+a");
} // unmatched bracket

确保您的完整代码中没有语法错误(如无法匹配的括号),并且始终存在其他情况,仅用于开发目的。

答案 1 :(得分:1)

悬挂其他歧义。您是否使用else子句匹配错误的if子句?这是一个常见错误。

这通常是由于格式不佳造成的。

这是你的代码:

int a=10, b=5;
if(a>b)
{
if(b>5)
System.out.println("b is:"+b);
 }
else
System.out.println("a is:"+a");
}

这是一个格式正确的代码:

int a=10, b=5;
if(a>b)
{
   if(b>5)
      System.out.println("b is:"+b);
}
else
   System.out.println("a is:"+a");
}

查看每个语句的缩进方式。很明显,else子句与外部if相关联。但是,在你的代码中很难看到。

您的IDE可以为您正确格式化代码。例如,如果您使用的是Eclipse,则可以选择代码并按Ctrl + I格式化代码。

答案 2 :(得分:0)

if(a>b) = true |没有输出

if(b>5) = false |无输出(原因:5不大于5)

else阻止没有被执行

答案 3 :(得分:0)

您的代码显示没有输出,因为> b但b = 5,不大于。要解决此问题,请将if(b>5)更改为if(b>=5)

答案 4 :(得分:0)

这是另一种重新格式化使问题更加清晰的案例。

    int a=10, b=5;
    if(a>b) { // 'true' - This block is executed
        if(b>5) // 5 is not greater than 5, it's equal, so this isn't executed
            System.out.println("b is:"+b);
    } else { // This is not executed
        System.out.println("a is:"+a);
    }

当一个错误变得混乱时,只需逐步执行该程序并按照编译器的想法进行思考。另外,如果您使用{ braces }语句的大括号,我建议为else语句形成一个带if的完整块,它会使事物更好地结合在一起,并且更容易阅读。确保事物缩进正确也使事情更容易理解。可读性很重要!

答案 5 :(得分:0)

int a=10, b=5;
if(a>b)
{
   if(b>5)
   System.out.println("b is:"+b);
}
else
   System.out.println("a is:"+a");}

在上面的代码中首先,如果你正在检查(a> b),即(10> 5)条件为真,那么首先在if内执行if if。 在你的第二个if条件(b> 5),即(5> 5)条件是假的。因此它终止了程序,因此它不会显示任何内容。 为了更好地理解,我按如下方式编辑代码:

int a=10,b=5;
if(a>b)          // This condition is true so this if block executed
{
      if(b>5)    // this is false so this block won't execute.
      {
          System.out.println("b is :"+b);
      }
}
else  // Alredy first if executed because true condition so this also not executing
{
      System.out.println("a is :"+a);               
}
// Thats why you don't get any output in this program.
相关问题