Hello,
I am to write a program that is capable of taking an array of doubles from the user, then calculating each numbers square, cube etc. and then displaying it to the screen. The program itself is fine, but one aspect of the program is that if a user enters something other than an integer, no error message needs to be displayed but just a re-prompt box.
I tried putting in a try and catch blocks, but I notice that when I make the condition of the catch statement to reprompt for the number, when the user enters it, the program jumps outside the catch block (as it should) and the program ends.
Is there a way I can make it jump back to the top of the code if NumberFormatException is thrown?
Here is my code:
import java.text.DecimalFormat;
import java.math.*;
import javax.swing.*;
public class SquareRootCube
{
public static void main (String[]args)
{
try
{
String indexAmount = JOptionPane.showInputDialog (null, "Please enter the amount of numbers you will enter");
int pIndex = Integer.parseInt(indexAmount);
while (pIndex <= 0)
{
JOptionPane.showMessageDialog (null, "That integer is not valid. Enter an integer greater than 0");
indexAmount=JOptionPane.showInputDialog(null, "Enter the amount of numbers you will enter");
pIndex = Integer.parseInt(indexAmount);
}
double numbers[] = new double[pIndex];
int index = 0;
for (index=0; index < pIndex; index++)
{
String sNumber = JOptionPane.showInputDialog (null, "Please enter an integer between 25 and 150");
numbers[index]= Integer.parseInt(sNumber);
while (numbers[index] < 25 || numbers[index] > 150)
{
JOptionPane.showMessageDialog (null, "That is not a valid number.");
sNumber = JOptionPane.showInputDialog (null, "Please enter an integer between 25 and 150");
numbers[index]= Integer.parseInt(sNumber);
}
}
double squared, squareRoot, cubed;
for (index=0; index < pIndex; index++)
{
DecimalFormat formatter = new DecimalFormat(",###.00");
squared = numbers[index] * numbers[index];
squareRoot = Math.sqrt (numbers[index]);
cubed = numbers[index] * numbers[index] * numbers[index];
String fSquared = formatter.format(squared);
String fSquareRoot = formatter.format(squareRoot);
String fCubed = formatter.format(cubed);
JOptionPane.showMessageDialog (null, numbers[index] + " squared is " + fSquared + "\n" + numbers[index] + " square root is " +fSquareRoot + "\n" + numbers[index] + " cubed is " + fCubed);
}
System.exit(0);
}
catch (NumberFormatException e)
{
sNumber = JOptionPane.showInputDialog (null, "Please enter an integer between 25 and 150");
numbers[index]= Integer.parseInt(sNumber);
}
}
}
Thanks in advance :)