-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSalesLoop.java
More file actions
38 lines (35 loc) · 1.7 KB
/
Copy pathSalesLoop.java
File metadata and controls
38 lines (35 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.Scanner;
/**
* Runs a loop that lets a user enter a number.
* It validates the input, then multiply the number by 10 and stores the result in a variable named 'sales'.
* The loop iterates if the input contains a value less than 100.
* The loop terminates with a response to the user if the value entered is 100 or greater and ends the program.
*/
public class SalesLoop {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Initialize the variables.
// value is initialized to -1 so do-while loop will execute at least once.
float value = -1.0f;
float sales;
String input;
// Loop that repeats until the input is a valid number greater than 100.
do { System.out.print("Enter a number: ");
input = scanner.nextLine();
// Check input is a valid non-negative number and assign it to value.
// RegEx pattern matches any decimal number (with or without a decimal point) in US n.nn or EU n,nn format.
if (input.matches("(\\d)*(\\.|,)?\\d+")) {
value = Float.parseFloat(input.replace(",","."));
// Check value is less than 100 and multiply by 10 and assign it to sales if it is.
if (value < 100.0f) {
sales = value * 10.0f;
System.out.printf("Sales: $%.2f%n", sales);
}
}
// Continue loop if input was either less than 100 or not a number.
} while (value <= 100);
// Inform the user the value entered was over 100.
System.out.printf("Value entered: \"%s\" is greater than 100.%n", input);
scanner.close();
}
}