Gabi Lee Gabi Lee - 1 month ago 17
Java Question

(Java) Trying to Use Try/Catch Block for Input

I have this homework assignment where I have to take input of a positive double and square it, but also have a try/catch block in case something other than a positive double (say, a negative number or a string) is input.

I've looked on SO to try and figure out how just to do that, and here's what I have so far:

import java.util.Scanner;
import java.util.InputMismatchException;
class C12hw2
{
public static void main(String[] args)
{
while(true)
{
try
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter non-negative double constant, please");
double number = Double.parseDouble(scanner.nextLine());
}
catch (InputMismatchException e)
{
System.out.println("That is not a double constant, please re-enter");
double number = Double.parseDouble(scanner.nextLine());
}
while(scanner >= 0) // line 18
{
System.out.println("The square of " + number + " is " + number*number); // line 20
}
}
}
}


I'm now getting an error that when I use "scanner" or "number" after I've declared them, that I never did declare them, and I'm really confused as to why that's popping up. (the errors are occurring at lines 18 and 20).

Answer

The scanner and number variables are defined inside a block. This means that they cannot be accessed outside of that block.

If you want to access them outside, you need to define them outside:

while(true)
{
    Scanner scanner; // defined outside the block
    double number;   // defined outside the block
    try
    {
        scanner = new Scanner(System.in);
        System.out.println("Enter non-negative double constant, please");
        number = Double.parseDouble(scanner.nextLine());
    }    
    catch (InputMismatchException e)
    {
        ...
    }
    while(scanner >= 0)
    {
        System.out.println("The square of " + number + " is " + number*number);
    }
}

You probably also have a problem with while(scanner >= 0).