TheLittleCoder - 10 months ago 50

Java Question

I want to check if the input my code needs is correct so I put a lot of if statements checking for the requirements and I can't figure out why it's not working. It is supposed to check if n is less or equal to 91 and / or it is a decimal (I don't want my input to be either). This is so that the user doesn't break the program by typing a decimal or a number higher than 91.

`while (Error == 1) {`

n = user_input.nextDouble();

if ((n - Math.round(n) <= 0.9) && (n - Math.round(n) >= 0.1)) {

System.out.println("Error: No Decimal points please, try again");

continue;

}

if ((n - Math.round(n) <= 0.9) && (n - Math.round(n) >= 0.1) && (n > 91)) {

System.out.println("Error: No Decimal points please, try again");

System.out.println("Error: Number too high, try again");

continue;

}

if (n > 91) {

System.out.println("Error: Number too high, try again");

continue;

}

if (n == Math.round(n)) {

Error = 0;

}

if (n == 0) {

break;

}

}

For some reason when I type 9.1 or 9.9 it doesn't do anything at all. It's blank...

Answer

Well, first of all, you seem to want only inputs that are integers less than or equal to 91. It seems strange that you would say this, but then explicitly grab doubles with the nextDouble() method of Scanner.

There are better ways of checking for integers... see this question What's the best way to check to see if a String represents an integer in Java?

Either way, I'll assume you intend on sticking with your *innovative* methodology:

You are correct, that in ** regular math**, 9.1 rounds to 9 and the difference between the two is less than or equal to 0.1. Your cases

But welcome to the world of Java floating point algebra! **Doubles don't compare well** here.
What do I meant that they don't compare well? Well, the difference between your '9.1' and '9' is actually *0.09999999999999964*, not 1.
Java doesn't compensate for this when you use basic comparators, so your comparison fails.

Hope is not lost! There is a better way of comparing doubles than using the regular comparison operators. Introducing.... Double.compare()!! You can read the javadocs on that method, or you can go here for information on what that method does: some reliable tutorial site

However, *what if they input 9.0001*? Your test fails, even if the comparison works as you'd expect. You really should rethink your math here. As in, try this instead:

```
Double.compare((n - Math.round(n)),0.0) != 0)
```

Source (Stackoverflow)