2
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。我该如何解决?

4

5 回答 5

2

这是因为您在 try 块中声明了变量,在 try 块之外声明它

于 2013-01-12T07:06:15.750 回答
1

像这样将您的choiceString移出try块,

String choiceString = "";
        try {
            Scanner input = new Scanner(System.in);
........
于 2013-01-12T07:38:06.957 回答
1

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

public static void operation() {
    String choiceString = "";
    try {
        ...
    } catch(StringException i) {
        System.out.println("You typed " + choiceString + i);
    }
}
于 2013-01-12T07:07:41.147 回答
1

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

于 2013-01-12T07:08:24.360 回答
1

choiceString 在 try 块中声明,因此在该范围内是本地的。您可以将choiceString 移到try-catch 块的外部,以使其在catch 块的范围内可用:

String choiceString = "";
try {
  //  omitted for brevity
} catch(StringException i) {
  System.out.println("You typed " + choiceString + i);
}
于 2013-01-12T07:08:25.597 回答