accepting integers and decimals

Quick question:

How would I change my code to accept both integers and decimals for my hrs variable?
This is my code:

//The getHours() method accepts the number of hours at home per week
public static int getHours()
{
//declare mehtod variables
int hrs = 0;
boolean done = false;

while (!done)
{
try
{

String message = "Enter the average number of hours
you are home per week

";

hrs = Integer.parseInt(JOptionPane.showInputDialog(null, message));

if (hrs < 1) throw new NumberFormatException();
else done = true;
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog(null, "Hours must be a positive number", "Error", JOptionPane.ERROR_MESSAGE);
}
}
return hrs;
}

Comments

  • : Quick question:
    :
    : How would I change my code to accept both integers and decimals for my hrs variable?
    : This is my code:
    :
    : //The getHours() method accepts the number of hours at home per week
    : public static int getHours()
    : {
    : //declare mehtod variables
    : int hrs = 0;
    : boolean done = false;
    :
    : while (!done)
    : {
    : try
    : {
    :
    : String message = "Enter the average number of hours
    you are home per week

    ";
    :
    : hrs = Integer.parseInt(JOptionPane.showInputDialog(null, message));
    :
    : if (hrs < 1) throw new NumberFormatException();
    : else done = true;
    : }
    : catch(NumberFormatException e)
    : {
    : JOptionPane.showMessageDialog(null, "Hours must be a positive number", "Error", JOptionPane.ERROR_MESSAGE);
    : }
    : }
    : return hrs;
    : }
    :
    :
    Change the variables to doubles, and parse strings into doubles.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion