写了一个练习,发现几处不明白的地方,这个是练习异常的,随机0-99的数,当除数=0的时候出现异常,然后记录下一共随机出了几个数,作业是完成了。可是请看下面,帮忙解答一下,谢谢了。public class Cho7Test3
{
public static void main(String[] args)
{
int k; //这里为什么一定要k=0,编译才通过,不然就报错 "可能未初始化变量k"
try{
test();
}catch(AriExp e){
e.printStackTrace();
k=e.GetI();
}finally{
System.out.println(k);
}
} public static void test() throws AriExp{
//为什么不能在变量a,b,c前面加public private protected 不然就报错 “非法的表达式开始”
int a; //这里为什么一定要a=0 ,编译才通过,不然就报错 "可能未初始化变量a"
int b;
int c;
try{
for(a=0;;a++){ //一直循环,直到b=0;然后记录下a的值
b=(int)(100*Math.random());
c=1000/b;
}
} catch (ArithmeticException e){
throw new AriExp(a);
}
}
}class AriExp extends Exception
{
protected int i;
public AriExp(){}
public AriExp(String s){
super(s);
}
public AriExp(int i){
super("AAAAAA");
this.i=i;
}
public int GetI(){
return i;
}
}
{
public static void main(String[] args)
{
int k; //这里为什么一定要k=0,编译才通过,不然就报错 "可能未初始化变量k"
try{
test();
}catch(AriExp e){
e.printStackTrace();
k=e.GetI();
}finally{
System.out.println(k);
}
} public static void test() throws AriExp{
//为什么不能在变量a,b,c前面加public private protected 不然就报错 “非法的表达式开始”
int a; //这里为什么一定要a=0 ,编译才通过,不然就报错 "可能未初始化变量a"
int b;
int c;
try{
for(a=0;;a++){ //一直循环,直到b=0;然后记录下a的值
b=(int)(100*Math.random());
c=1000/b;
}
} catch (ArithmeticException e){
throw new AriExp(a);
}
}
}class AriExp extends Exception
{
protected int i;
public AriExp(){}
public AriExp(String s){
super(s);
}
public AriExp(int i){
super("AAAAAA");
this.i=i;
}
public int GetI(){
return i;
}
}
public static void main(String args[]) {
int iteration = 0; // Store the iteration number. // ***
try {
loopy(); // Call the method that will throw the exception.
} catch(IteratedArithmeticException e) {
System.out.println(e);
iteration = e.getIteration(); // ***
} finally { // ***
System.out.println("Arithmetic exception occurred at iteration "+iteration); // ***
} // ***
} // This method throws an exception - eventually:
static void loopy() throws IteratedArithmeticException {
int iteration; // 他这边为什么不用赋值就可以通过编译啊
int result; // Stores a result
int divisor; // Random divisor // Loop will continue until an exception is thrown:
for(iteration=0;;iteration++)
try {
divisor = (int)(100*Math.random()); // Generate a random divisor.
result = 1000/divisor; // If we hit zero - bingo!
} catch(ArithmeticException e) {
throw new IteratedArithmeticException(iteration);
}
}
}
//这里为什么一定要k=0,编译才通过,不然就报错 "可能未初始化变量k"
一:a=0的原因:在java语言中,成员变量都有默认值,如(默认int、short、等都为0),但是在方法里面的局部变量则没有默认值,使用前一定要给它赋值
如你吧a写在mian方法外,则不赋值也可以通过编译;
二: //为什么不能在变量a,b,c前面加public private protected 不然就报错 “非法的表达式开始” 原因:在一个方法里面的局部变量只能在这个方法里面被使用,在方法外不能被使用,你说在方法里面加上权限(public,protected,private)有意义吗?
你都觉得没意义,那JVM会那么傻。所以,在方法里加权限会出现编译错误的;三://这里为什么一定要a=0 ,编译才通过,不然就报错 "可能未初始化变量a"
这里不一定要a=0啊,因为你声明了,但还没有开始使用来的,在你程序中,你使用的时候,他赋值了,即:for(a=0;;a++){ //a赋值为0
如a不赋值,则解释如一,test()也是一个方法,在test()方法里面的局部变量没默认值,使用时候会宝错;
2,heap
3,code segment
4,还有一个地方忘记了,,方正是放 静态变量和字符串常量的敌方