简体   繁体   中英

Eclipse, I keep subtracting a while-loop value, and it won't give me the correct answer

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);
    }
}

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;
        }

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM