if I'm entering a string like hello
the program will work and say there is an error and ask user to input a radius again, but if I enter something like Hello World 123
it will give me the error and the calculation. How can I check the input and make it stay in the loop if there is string characters entered?
import java.util.Scanner;
public class ComputeArea {
public static void main(String[] args) {
double radius; //define radius variable
double area; //define area variable
double pie = 3.14159; //define pie as 3.14159
boolean inputIsAString = false;
//Import Scanner library to allow user to input value
System.out.print("Please enter radius to calculate area: ");
Scanner input = new Scanner(System.in);
//Is the input a number? If not print error and redirect to input statement
while (!input.hasNextDouble() && !inputIsAString) {
System.out.println("");
System.out.println("*********************************");
System.out.println("Error Please enter a valid number");
System.out.println("*********************************");
System.out.println("");
System.out.print("Please input radius: ");
input.next();
if (input.next().matches("[a-zA-Z]")) {
System.out.println("user enter string");
inputIsAString = true;
} else {
inputIsAString = false;
}
}
//Calculate the area with the given radius
radius = input.nextDouble();
area = radius * radius * pie;
//Print out the area
System.out.println("The area of a circle with a radius of " + radius + " is equal to: " + area);
}
}