异常处理错误:找不到符号变量

时间:2013-01-12 07:03:22

标签: java exception exception-handling

public static void operation() {
    try {
        Scanner input = new Scanner(System.in);
        String choiceString = "";
        char choice = 'a';
        System.out.print("Enter letter of choice: ");
        choiceString = input.next();
        if (choiceString.length() == 1) {
            choice = choiceString.charAt(0);
            System.out.println("-------------------------------------------");

        switch(choice) {
            case 'a': {
                ....
                break;  
            }
            case 'b': {
                ....    
            }
            default:
                throw new StringException("Invalid choice...");
        }
        }else {
            throw new StringException("Invalid input...");
        }
    } catch(StringException i) {
        System.out.println("You typed " + choiceString + i);
    }

当程序提示用户输入选择的字母,并且用户输入单词或数字时,它应该捕获异常。它应该显示此输出:

You typed: ashdjdj
StringException: Invalid input...

问题在于,它无法找到变量choiceString。我该如何解决这个问题?

5 个答案:

答案 0 :(得分:2)

这是因为你在try块中声明了变量,在try块

之外声明它

答案 1 :(得分:1)

你的问题是try块中声明的变量范围在相应的catch块中是不可见的。要修复编译错误,请在try之外声明变量,如下所示,

public static void operation() {
    String choiceString = "";
    try {
        ...
    } catch(StringException i) {
        System.out.println("You typed " + choiceString + i);
    }
}

答案 2 :(得分:1)

在try catch块之外声明choiceString,它应该解决问题

答案 3 :(得分:1)

choiceString在try块中声明,因此是该范围的本地。你可以将choiceString移动到try-catch块的外部,你需要它在catch块的范围内可用:

String choiceString = "";
try {
  //  omitted for brevity
} catch(StringException i) {
  System.out.println("You typed " + choiceString + i);
}

答案 4 :(得分:1)

将你的choiceString移出try块,就像这样,

String choiceString = "";
        try {
            Scanner input = new Scanner(System.in);
........