0

So I'm trying to include a dollar test in my program that checks if the value inputted by the user is a possible dollar amount. I'm having troubles with it subtracting .01 in the while-loop. The idea is if they enter a value with 3 decimal places like 2.345, it'll catch it and have the input a valid number. Does anyone have any advice on how to fix this problem?

Scanner input = new Scanner(System.in);

double dollar = 0;

    System.out.print("Please enter a dollar amount: ");
    dollar = input.nextDouble();

    while (dollar != 0){
        dollar -= .01;
        if (dollar < 0)
            {System.out.print("Please enter a valid dollar amount: ");
            dollar = input.nextDouble();
            }   
        System.out.println(dollar);
    }
}
Raju
  • 2,902
  • 8
  • 34
  • 57
spartan17
  • 19
  • 5

1 Answers1

0

I have updated your code piece with validations in while loop structure. This loop will break only when all the below condition satisfies

  • User input >0.01 $
  • User input is positive value
  • User input is having only two decimal values

You can try below code

import java.util.Scanner;   
public class Testing {
    public static void main(String args[])
    {
        Scanner input = new Scanner(System.in);
        double dollar = 0;
        System.out.print("Please enter a dollar amount: ");
        dollar = input.nextDouble();
        System.out.println("Your value :" + dollar);
        String text = Double.toString(Math.abs(dollar));
        int integerPlaces = text.indexOf('.');
        int decimalPlaces = text.length() - integerPlaces - 1;
        dollar -= .01;
        while (dollar == 0 | dollar < 0 | decimalPlaces>3){
            System.out.print("Please enter a valid dollar amount: ");
            dollar = input.nextDouble();
            System.out.println(dollar);
            text = Double.toString(Math.abs(dollar));
            integerPlaces = text.indexOf('.');
            decimalPlaces = text.length() - integerPlaces - 1;
            dollar -= .01;
        }

    }

}
Raju
  • 2,902
  • 8
  • 34
  • 57
  • I see what you mean, but what if the user input 50.991? That's the part I'm trying to figure out is if he enters to many decimal places. – spartan17 Feb 21 '16 at 04:22
  • Put another check in while condition & cross check decimal digits – Raju Feb 21 '16 at 04:26
  • You can use ` toString().length() ` , also this link might help --> http://stackoverflow.com/questions/6264576/number-of-decimal-digits-in-a-double – Raju Feb 21 '16 at 04:35