Java Try-Catch问题与扫描仪

时间:2018-01-17 20:47:04

标签: java try-catch java.util.scanner

我有一个用于处理Java中的错误ArithmeticError的代码。但是当我在代码中使用变量n和m时,ElementNotFound有一个编译错误。 代码:

import java.util.*;
class Abc {
    public static void main(String args[] ) throws Exception {
        Scanner sc = new Scanner(System.in);
        try{
            int n = sc.nextInt();
            int m = sc.nextInt();
            if(m < 0 || n < 0){
                throw new ArithmeticException();
            }
        }
        catch(ArithmeticException ex){
            System.out.println("Invalid!");
        }
        int i = 1,k=0;
        while( (i * i )  <= (m + n)){  // Error in this line m and n not found
            if((i * i) == (m + n)){  // Error in this line also
                k = 1;  
                break;
            }
            i += 1;
         }
         if(k == 1){
             System.out.println(i);
         }
         else{
             System.out.println("-1");
         }
   }
}

在删除try catch块时,代码将按预期编译并运行。

错误: 错误:找不到符号   而((i * i)&lt; =(m + n))^   符号:变量m   地点:班级Abc

abc.java:32:错误:找不到符号   而((i * i)&lt; =(m + n))^   符号:变量   地点:班级Abc

abc.java:35:错误:找不到符号                 if((i * i)==(m + n))                                ^   符号:变量m   地点:班级Abc

abc.java:35:错误:找不到符号                 if((i * i)==(m + n))                                    ^   符号:变量   地点:班级Abc

4个错误

1 个答案:

答案 0 :(得分:1)

在try-catch博客之外初始化m和n。 m和n现在已超出范围。

Scanner sc = new Scanner(System.in);
    int n = 0;
    int m = 0;
    try{
        n = sc.nextInt();
        m = sc.nextInt();
        if(m < 0 || n < 0){
            throw new ArithmeticException();
        }
    }
    catch(ArithmeticException ex){
        System.out.println("Invalid!");
    }
    int i = 1,k=0;
    while( (i * i )  <= (m + n)){  // Error in this line m and n not found
        if((i * i) == (m + n)){  // Error in this line also
            k = 1;  
            break;
        }
        i += 1;
     }
     if(k == 1){
         System.out.println(i);
     }
     else{
         System.out.println("-1");
     }