So my question is on this: This program is supposed to calculate the area of circle the user inputs a number comes out with the answer also any invalid input is not allowed i use the try-catch but it wont work...
Thank you so much for you time everyone :))
Here is the code:
import java.util.Scanner;
import java.io;
/**
*
* @author Osugule
*/
public class AreaCircle {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner sc = new Scanner(System.in); // read the keyboard
System.out.println("This program will calculate the area of a circle");
System.out.println("Enter radius:");//Print to screen
double r = sc.nextDouble(); // Read in the double from the keyboard
double area = (3.14 *r * r);
try {
}
catch( NumberFormatException e ) {
System.out.println("Invalid Input, please enter a number");
//put a message or anything you want to tell the user that their input was weird.
}
String output = "Radius: " + r + "\n";
output = output + "Area: " + area + "\n";
System.out.println("The area of the circle is " + area);
}
}
I edited the answer so it will ask the user again if the input is wrong
You need to put nextDouble in the try clause:
Note that I added the line after the try-catch to the try clause, as if you fail to parse the number, they should not be printed.
You should put these two lines -
inside the
try
block -From the documentation -
So if you enter an invalid character,
sc.nextDouble()
is probably throwing anInputMismatchException
which won't be caught by thecatch
block because it only catcherNumberFormatException
. So your program will terminate after throwing an exception but you won't get any messages.To handle this scenario also, add the following block, just under your current
catch
block -You must catch
InputMismatchException
exception like this: