Reputation: 197
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);
}
When the program prompts the user to enter the letter of choice, and the user enters a word or a number, it should catch the exception. It should display this output:
You typed: ashdjdj
StringException: Invalid input...
Problem here is, it could not find the variable choiceString. How do I fix this?
Upvotes: 2
Views: 3244
Reputation: 551
move your choiceString out of try block like this,
String choiceString = "";
try {
Scanner input = new Scanner(System.in);
........
Upvotes: 1
Reputation: 6484
choiceString is declared in the try block and therefore local to that scope. You can move choiceString to the outside of the try-catch block of you need it to be available in the catch block's scope:
String choiceString = "";
try {
// omitted for brevity
} catch(StringException i) {
System.out.println("You typed " + choiceString + i);
}
Upvotes: 2
Reputation: 2429
Declare choiceString outside try catch block and it should solve the problem
Upvotes: 1
Reputation: 916
Your problem is that the scope of variables declared in the try block will not be visible from the corresponding catch block. To fix the compilation error, declare the variable outside the try like so,
public static void operation() {
String choiceString = "";
try {
...
} catch(StringException i) {
System.out.println("You typed " + choiceString + i);
}
}
Upvotes: 1
Reputation: 483
It is because you have declared variable inside try block declare it outside of try block
Upvotes: 2