Darw1n34
Darw1n34

Reputation: 19

Basic Java - validating for interval decimals

I am struggling with this. I know how to write the code to determine if a number is between 1.0 and 10.0. Assume that the noOfJudges is a valid input (between 3 and 9)

for(noOfJudges = 0; noOfJudges < scores.length; noOfJudges++) {  
  scores[noOfJudges]=console.nextDouble();
  while((scores[noOfJudges] < 1.0)||(scores[noOfJudges] > 10.0)) {
    System.out.print("Please reenter the score (must be between 1.0 and 10.0, in .5 increments): ");
    scores[noOfJudges] = console.nextDouble();
    System.out.println();
  }
  System.out.println();

A valid input for the variable would be between 1.0 and 10.0, in 0.5 increments i.e. 4.2 is not a valid input, but 4.5 is. Not sure how to proceed here...

Upvotes: 1

Views: 299

Answers (2)

M Sach
M Sach

Reputation: 34424

use something like this

   for(double i = 1; i < 10.0; i+=0.5) {
//...
}

see the link for-loop, increment by double how you can usr integer loop to prevent being bitten by artifacts of floating point arithmetic

Upvotes: 0

Zim-Zam O&#39;Pootertoot
Zim-Zam O&#39;Pootertoot

Reputation: 18158

Multiply the input by 2 and check if it's between 2.0 and 20.0, then truncate the decimal places by casting it to an int and check if the truncated value equals the original value (d == (double)(int)d), or alternatively round the input and see if it equals the original input (d == Math.round(d))

Upvotes: 2

Related Questions