How do I use try-catch to validate input?
Hi I seem to need help here again. I am not sure how to use the try-catch method to make sure that the user inputs only numbers, and if the user inputs anything else, it will give an error and prompt the user to enter the numbers again.
here is the part of the code where I ask for all of the numbers.
thanks.
Code :
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = 1;
double s1 = 0.0, s2 = 0.0, s3 = 0.0;
double base = 0.0, height = 0.0;
System.out.println("Welcome to the Triangle program");
while(count >= 1){
System.out.println("Enter side 1: ");
s1 = sc.nextDouble();
System.out.println("Enter side 2: ");
s2 = sc.nextDouble();
System.out.println("Enter side 3: ");
s3 = sc.nextDouble();
System.out.println("Enter the base: ");
base = sc.nextDouble();
System.out.println("Enter the height: ");
height = sc.nextDouble();
}
Re: How do I use try-catch to validate input?
The basic format would be like this:
Code java:
while(true) {
try {
// Code to evaluate goes here.
// In other words code that could throw an exception.
} catch (Exception e) {
// Tell the user they did something wrong.
// If you know the specific exception to catch the replace Exception with it.
}
}
One more piece of information for you. When the Scanner expects a certain type of input and the Exception is caught, the Scanner will not advance to the next input until a method (one of the Scanner methods) is called to make it advance.
Re: How do I use try-catch to validate input?
What KucerakJM said is right, your looking to catch if there is a non-number input, so the exception would be the NumberFormatException.
[quote]
Code :
while(true) {
try {
// Code to evaluate goes here.
// In other words code that could throw an exception.
} catch (NumberFormatException e) {
// Tell the user they did something wrong.
// If you know the specific exception to catch the replace Exception with it.
}
}