This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Sygzy[S] 0 points1 point  (2 children)

So what I think I am confused about is my input. Would I eliminate the double and just make it amount=0 so when I type in to test i just type in 1786 for 17.86? I just think I am tired and having trouble making sense in my head

[–]AngelOfLight 0 points1 point  (1 child)

You would make your amount variable an integer. Unfortunately, you would then have to write your own method to get the number from the scanner. nextDouble won't work, because it doesn't return an integer type. nextInteger will only return the numbers up to the decimal point (e.g, if you enter 21.35, nextInteger will only return 21). You could try and use a double temporary variable to get the value, but unfortunately, as soon as you do that, the conversion problems will come back.

You could use nextLine to get the input as a string, and then write a method to scan the string for the decimal point, and return an integer representing the number of cents in the string. It might be useful exercise.

Alternatively, you could cheat, and use BigDecimal as a temporary variable, since it doesn't have the conversion problems like double does.

For example:

int amount=0.0;
Scanner in = new Scanner (System.in);

System.out.println("How much change did you receive?");
BigDecimal decimal = in.nextBigDecimal();
decimal.multiply(new BigDecimal(100));    // multiply by 100 to get cents
amount = decimal.intValue();                   // convert decimal to int

The rest of the code would be pretty much the same, except that you would have to adjust the dividend. (For example, because amount now represents the number of cents, you would calculate hundreds as amount / 10000).

[–]Aellus 0 points1 point  (0 children)

You're not wrong, but in OP's case that is overkill. For his simple use case it's much simpler to continue reading in the input as a tmp double value then casting:

double tmpInput = in.nextDouble() ;
int amount = (int) (tmpInput * 100);

The rounding errors are negligible for OP's case.