Reputation: 13
The goal of this program is to find the area of a circle with 4 points that the user types, if the user types anything but a integer I want a message to output ("numbers only")
package areacircleexception;
import java.util.Scanner;
public class AreaCircleException {
public static double distance
(double x1, double y1, double x2, double y2)
{
double dx = x2 - x1;
double dy = y2 - y1;
double dsquared = dx*dx + dy*dy;
double result = Math.sqrt (dsquared);
return result;
}
public static double areaCircle(double x1, double y1, double x2, double y2)
{
double secretSauce = distance(x1, y1, x2, y2);
return areaCircleOG(secretSauce);
}
public static double areaCircleOG(double secretSauce)
{
double area = Math.PI * Math.pow(secretSauce, 2);
return area;
}
I think my problems have something to do with this method below..
public static int getScannerInt (String promptStr){
Scanner reader = new Scanner (System.in);
System.out.print ("Type The x1 point please: ");
int x1 = reader.nextInt();
return 0;
}
public static void main(String[] args)
{
Scanner reader = new Scanner (System.in);
boolean getScannerInt = false;
while(!getScannerInt)
{
try
{
System.out.print ("Type The x1 point please: ");
int x1 = reader.nextInt();
System.out.print ("Type The x2 point please: ");
int x2 = reader.nextInt();
System.out.print ("Type The y1 point please: ");
int y1 = reader.nextInt();
System.out.print ("Type the y2 point please: ");
int y2 = reader.nextInt();
double area = areaCircle(x1, x2, y1, y2);
System.out.println ("The area of your circle is: " + area);
getScannerInt = true;
}
catch(NumberFormatException e)
{
System.out.println("Please type in a number! Try again.");
} }
}
}
other than the Exception the program works correctly but when I type a string it does not handle my Exception and i cant figure out why.
Upvotes: 1
Views: 73
Reputation: 2121
You are not catching the right Exception
. That is why you never go into the catch
when you enter a String
. Using a String throws a InputMismatchException
not a NumberFormatException
. You can change your catch statement to catch all Exception
's by doing something like this:
catch(Exception e){...}
Edit: Even with the above change, you might end up in an infinite loop. To fix this, you need to get to the end of the line every iteration of your while loop that you enter the catch block. Change your catch block to this and you should be good:
catch(Exception e){
System.out.println("Please type in a number! Try again.");
reader.nextLine();
}
Upvotes: 2
Reputation: 17534
When you call nextInt, and your next input isn't a valid integer, the exception you get is a :
java.util.InputMismatchException
Also, rather than waiting for an exception, you may call
hasNextInt()
This method returns true if the next incoming token is an integer, false otherwise.
Upvotes: 2