1

I have a program, which takes a parameter from the args[] array, defined in the main method, but has a backup in case that isn't defined, in the form of a try...catch block, which, if an ArrayIndexOutOfBounds exception is thrown, instead uses a method called getInt to prompt the user to enter a variable. But, for some reason, when I try to use that variable, my compiler says that it cannot find it. I have the following code:

try {
    int limit = Integer.parseInt(args[0]);
}
catch(ArrayIndexOutOfBoundsException e) {
    int limit = getInt("Limit? ");
}
int[] p = getPrimes(limit);

getPrimes is another method I have, which returns an array of prime numbers starting from 2 and up to a specified number (using the Sieve of Atkin). Anyway, when I write int[] p = getPrimes(limit); and try compiling, it says that the "limit" variable is not defined. Help please!

4 Answers 4

8

You should declare it outside the block:

int limit;
try {
    limit = Integer.parseInt(stuff[0]);
}
catch(ArrayIndexOutOfBoundsException e) {
    limit = getInt("Limit? ");
}
int[] p = getPrimes(limit);
Sign up to request clarification or add additional context in comments.

Comments

2

declare limit outside of catch block, currently it is under the scope of catch block catch{}

Comments

2
int limit;
try {
    limit = Integer.parseInt(stuff[0]);
}
catch(ArrayIndexOutOfBoundsException e) {
    limit = getInt("Limit? ");
}
int[] p = getPrimes(limit);

In your program you have created 2 local Limit variable one in try block and another in catch block.

Declare it outside the try block

Comments

1

Define limit variable outside of try/catch block, you do not have access to variables defined inside try block outside. You would also have to initialize it if you are calling it outside of try block as in your case here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.