public class TestReturn {
public static void main(String[] args){
testNum();
try{
int a = 5;
}catch(Exception e){
e.printStackTrace();
}
a = 6;//这样写为什么会报错.在前面不是定义了a值了吗? 报错说没有声明变量
}
public static void testNum(){
int a = 5;
a = 6;
System.out.println(a);
}
}
所以当出了}时就被清空了
public class TestReturn {
public static void main(String[] args){
int a ;
testNum();
try{
a=5;
}catch(Exception e){
e.printStackTrace();
}
a = 6;
}
public static void testNum(){
int a = 5;
a = 6;
System.out.println(a);
}
} 这样写就没错了,你要分清实例变量跟局部变量,看一下书,打一下代码就可以分清了。
try{
int a = 5;
}catch(Exception e){
e.printStackTrace();
}
a = 6;//这样写为什么会报错.在前面不是定义了a值了吗? 报错说没有声明变量 注意 a的范围问题
要在TRY语句块外定义才行。可以在语句块内赋值
public static void main(String[] args){
testNum();
try{
int a=5;
a = 6; }catch(Exception e){
e.printStackTrace();
}
}
public static void testNum(){
int a = 5;
a = 6;
System.out.println(a);
}
}
try{}里的为局部变量
public class TestReturn {
public static void main(String[] args){
int a ;
testNum();
try{
a=5;
}catch(Exception e){
e.printStackTrace();
}
a = 6;
}
public static void testNum(){
int a = 5;
a = 6;
System.out.println(a);
}
}
用高级点的开发工具自动会提示这种错误,如:eclipse
int a = -1;
try{
xxx...
}catch(Exception e){
e.printStackTrace();
}
a = 6;
int a = 5;你这句话放在try里面,相当于是一个局部变量。。
只要把这个拿到try外面就OK了