public class Test{ int x=-10 ,y=0 ;
y=x>=0?x:-x;
public static void main(String[]args)
{
System.out.println("the abs of "+x+" is "+y);
}
}
总提示:Test.java:4 错误: 需要<标识符>
y=x>=0?x:-x;
 ^改为下面的代码则不会出错。为什么?
public class Test{ public static void main(String[]args)
{

int x=-10 ,y=0 ;
y=x>=0?x:-x;
System.out.println("the abs of "+x+" is "+y);
}
}
谢谢!  ^

解决方案 »

  1.   

    看这个 你就明白了 
    http://topic.csdn.net/u/20091221/19/ef37eceb-6f8e-40ee-8695-7b132c2f292f.html
      

  2.   

    y=x>=0?x:-x; 类里的语句只能是定义变量或方法! 可执行的语句只能在方法里或者{}(代码块)里。
    上面的语句不是变量定义语句,不是方法定义,不在代码块{}里,所以报错!
      

  3.   

    我曾经老喜欢犯这种错。你定义个变量时可以顺带赋值,但是如果你在方法之外再给他赋值就会报这个错。要么定义一个方法来在该方法中赋值,要么在main中(main也是函数)