public class TestException{
public static void main(String[] args){
System.out.println("Please input number 1:");
int number1 = Keyboard.getInteger();
System.out.println("Please input number 2:");
int number2 = Keyboard.getInteger();
System.out.println(number1+"/"+number2);
try{
int result = number1/number2;
}
catch(ArithmeticException ae){
System.out.println("不能为0");
}
//System.out.println(result); 如果这里不注释就要出错,出错见最后
}
}import java.io.*;
public class Keyboard{
static BufferedReader InputStream = new BufferedReader(new InputStreamReader(System.in));
public static int getInteger(){
try{
return(Integer.valueOf(InputStream.readLine().trim()).intValue());
}
catch(Exception e){
e.printStackTrace();
return 0;
}
}
public static String getString(){
try{
return(InputStream.readLine());
}catch(IOException e){
return("0");
}
}
}出错原因是:
D:\java>javac TestException.java
TestException.java:14: 找不到符号
符号: 变量 result
位置: 类 TestException
                        System.out.println(result);
                                           ^
1 错误
——————————————————————————————————————————————
上面二个类,从键盘输入数字,但是我就不知道为什么找不到result,这里用了try就不能找到result了吗?
还有我在TestException.java编译的时候,如果不用try 除数为0,就能找到result,请问高手这是什么问题哦
谢谢回答

解决方案 »

  1.   

    这是局部变量作用域问题
    这是因为main函数中result的声明在try内所以他的作用域或者说有效范围应该在try{}之间
    所以只需要在try块外声明result即可.
    主要代码如下:
    .
    .
    .
    int result=0;
    try {
            result = number1 / number2;
    } catch (ArithmeticException ae) {
    System.out.println("不能为0");
    } catch (Exception ex) {
    System.out.println(ex.getMessage());
    }
    .
    .
    .
      

  2.   

    楼下的朋友能帮我继续回答这个问题吗?
    就是
    如果我按照我原来的,改成


    . try   { 
         public int  result   =   number1   /   number2; //加上了public,但是提示错误
    }   catch   (ArithmeticException   ae)   { 
    System.out.println("不能为0"); 
    }   catch   (Exception   ex)   { 
    System.out.println(ex.getMessage()); 




    ————————————————————
    错误提示是:
    D:\java>javac TestException.java
    TestException.java:10: 非法的表达式开始
                              public result = number1/number2;
                              ^
    1 错误
      

  3.   

    因为变量的作用域问题。你定义的result是在try{}的作用域,一旦出了try,这个result变量就消亡了你把  result 变量在上头定义一下就行了。
    int result = 0;
    然后在try{ result   =   number1/number2; }里使用这个变量就行了
      

  4.   

    去掉public,方法中不能有public关键字的