0

Please help.

Statement needs to print:

"Please enter the insured value of your home as a whole number: "

Which is simple but if I enter a double the another statement prints that reads: "You must only enter an integer: "

That is where I'm stuck. Any way I do it I get fatal logic errors.

Here is my code starting with declared variable and skipping the in between code:

double homeInsVal = 0.0;

<other code>

System.out.printf("%nPlease enter the insured value of your home as a whole  number:  "); 
homeInsVal = input.nextDouble();
{
 if (homeInsVal >= 0.0)
 {
  System.out.printf("%nYou must only enter an integer:  ");
  homeInsVal = input.nextInt(); 
 }
}

My logic is completely off. The reason why I declare homeInsVal as a double is because if I declare it as a Int as soon as I enter a decimal to purposely prompt the second statement I get a logic error an my code terminates but the way I currently have the code written the second prompt will print even if I enter an integer.

Please help!

Note: This is an intro Java class and while beggars can't be choosers have please explain as simple as possible. Thanks!

CQ1989
  • 1

2 Answers2

0

Not very clear as to what is the question. If you would want to check if the entered value is an integer or a Double, you can refer the below posts

How to find out if the value contained in a string is double or not

How to check if a double value has no decimal part

Community
  • 1
  • 1
0

You want an integer, but the user can enter what they like, including letters and other rubbish. But you can be sure the user enters something, ie a String. Also, to send the data to your program, the user will press Enter, which puts newline char(S) into the buffer.

What does this all mean? It means you need something like this:

String line = input.nextLine();
try {
    Integer number = Integer.parseInt(line);
} catch (NumberFormatException e) {
    // input wasn't a number
}

This isn't the whole story, but hopefully you can build on it.

Bohemian
  • 412,405
  • 93
  • 575
  • 722