请看如下程序public class Test3
{
  public static void main(String[] args)
   {
   int x=10;
   if(x>10)
     {
      int y;
      y=3;
      System.out.println("y="+y);
         
     }
     System.out.println("x="+x);
      
   } 
为什么只输出x=10,而y不输出????? 

解决方案 »

  1.   

    因为x=10,不满足x>10的条件,所以直接跳过if语句。。
      

  2.   

    这个问题看似很愚蠢,但是如果你将程序改一下
    public class Test
    {
      public static void main(String[] args)
       {
       int x=10;
       if(x<100)
       {
          int y;
          y=x;
          System.out.println("x="+x);
          System.out.println("y="+y); 
       }
         System.out.println("y="+y);     
       
       }
     }  
    结果呢???
      

  3.   

    看错了 把if看成for去了 
      

  4.   

    有啊!!!!
    public class Test 

      public static void main(String[] args) 
       { 
       int x=10; 
       if(x <100) 
       { 
         int y; 
         y=x; 
          System.out.println("x="+x); 
          System.out.println("y="+y); 
       } 
         System.out.println("y="+y);    } 
      }
    该程序是无法编译的!会提示找不到符号y!!
    再将程序改一下
    public class Test12

      public static void main(String[] args) 
       { 
       int x=10; 
       if(x <100) 
       { 
         int y; 
         y=x; 
          System.out.println("x="+x); 
          System.out.println("y="+y); 
       }      
       } 
      } 
    编译可以通过,却抛出了异常!!
    我想说明的是作用域的问题,变量y的作用域只在if块中,所以在mian方法中是不能访问的!! 
      

  5.   

    应该会报错吧,y的作用域只在if内有效
      

  6.   

    因为x=10,不满足x>10的条件,所以直接跳过if语句。。