import javax.swing.JOptionPane;
public class Program2
{
public static void main(String[] args)
{
Object[] options = {"2", "3"};
int again, num1, num2, num3;
String input1, input2, input3;
JOptionPane.showMessageDialog(null, "Welcome to the Greatest Common Factor Game!");
do
{
Object entry = JOptionPane.showOptionDialog(null, "Would you like to enter 2 or 3 numbers?", "GCF Game", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if(entry.equals(0))
{
input1 = JOptionPane.showInputDialog(null, "Please enter a whole positive number.").trim();
num1 = Integer.parseInt(input1);
input2 = JOptionPane.showInputDialog(null, "Please enter your second whole positive number.").trim();
num2 = Integer.parseInt(input2);
if(num1 < 0 || num2 < 0)
JOptionPane.showMessageDialog(null, "Invalid entry. Please follow the rules.");
else
JOptionPane.showMessageDialog(null, "The GCF is: " + gcf(num1, num2));
}
else if(entry.equals(1))
{
input1 = JOptionPane.showInputDialog(null, "Please enter a whole positive number.").trim();
num1 = Integer.parseInt(input1);
input2 = JOptionPane.showInputDialog(null, "Please enter your second whole positive number.").trim();
num2 = Integer.parseInt(input2);
input3 = JOptionPane.showInputDialog(null, "Please enter your third whole positive number.").trim();
num3 = Integer.parseInt(input3);
if(num1 < 0 || num2 < 0)
JOptionPane.showMessageDialog(null, "Invalid entry. Please follow the rules.");
else
JOptionPane.showMessageDialog(null, "The GCF is: " + gcf(gcf(num1, num2),num3));
}
again = JOptionPane.showConfirmDialog(null, "Would you like to play again?");
if(again == JOptionPane.NO_OPTION)
JOptionPane.showMessageDialog(null, "Thank you for playing! Goodbye!");
}
while(again == JOptionPane.YES_OPTION);
System.exit(0);
}
public static int gcf(int a, int b)
{int c;
while (b != 0)
{
c=b;
b=a%b;
a=c;
}
return a;
}
}
How to catch Input Errors?
Page 1 of 12 Replies - 3014 Views - Last Post: 06 September 2007 - 10:41 AM
#1
How to catch Input Errors?
Posted 05 September 2007 - 11:06 AM
I am trying to make a greatest factor game and the code will run fine but I'm not sure how to use the try catch function to catch an error, such as if the user enters letters and symbols instead of numbers. What exception catch do i do?
Replies To: How to catch Input Errors?
#2
Re: How to catch Input Errors?
Posted 05 September 2007 - 11:35 AM
Hi well you can use NumberFormatExceptionclass in the try block there should be all of the parsing integer things, then just catch it. You can also try to write your own exception.
#3
Re: How to catch Input Errors?
Posted 06 September 2007 - 10:41 AM
Page 1 of 1

New Topic/Question
Reply


MultiQuote




|