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
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.