String b, h;
char b1, h1;
do
{
b = JOptionPane.showInputDialog(null, "Enter the base of the triangle.");
h = JOptionPane.showInputDialog(null, "Enter the height of the triangle.");
b1 = b.charAt(0);
h1 = h.charAt(0);
if (b1 >= '0' && b1 <= '9' && h1 >= '0' && h1 <= '9') //This if statement will only execute the program if a number is entered
{
double base = Double.parseDouble(b);
double height = Double.parseDouble(h);
double area = (base*height)/2;
JOptionPane.showMessageDialog(null, "The area of a triangle with a base of " + base + " inches and a height of "
+ height + " inches is " + area + " inches.");
}
else
{
JOptionPane.showMessageDialog(null, "One or more of the values you entered is not a number. Please enter a number.");
}
}
while (!(b1 >= '0' && b1 <= '9' && h1 >= '0' && h1 <= '9')); /*Causes the statement to keep asking for a value until a number
is entered*/
break;
I have to write a program that will give the user the area or volume of a shape, depending on what they input/choose. The section above is for the area of a triangle. The program will keep asking for the value of the base and height until both values inputted are numbers. The only time an error comes is when the user clicks "OK" on the dialog box, without entering any value. The source of the error seems to be when the program attempts to convert the string to a char. How can I make it to where clicking "OK" without entering a value will not result in an error?
Here is the error itself
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String
index out of range: 0
at java.lang.String.charAt(Unknown Source)
at Shapes.area(Shapes.java:40)
at Shapes.main(Shapes.java:11)