-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHypotenuse Java Program.java
More file actions
67 lines (56 loc) · 2.19 KB
/
Hypotenuse Java Program.java
File metadata and controls
67 lines (56 loc) · 2.19 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.util.Scanner;
public class Main {
public static double readPositiveDouble(Scanner scanner, String prompt) {
double value = -1;
while (true) {
System.out.print(prompt);
if (scanner.hasNextDouble()) {
value = scanner.nextDouble();
if (value > 0) {
break;
} else {
System.out.println(" Please enter a number greater than 0.");
}
} else {
System.out.println("Invalid input. Please enter a valid number.");
scanner.next();
}
}
return value;
}
public static int readPositiveInt(Scanner scanner, String prompt) {
int value = -1;
while (true) {
System.out.print(prompt);
if (scanner.hasNextInt()) {
value = scanner.nextInt();
if (value >= 0) {
break;
} else {
System.out.println(" Please enter 0 or a positive number.");
}
} else {
System.out.println(" Invalid input. Please enter a valid integer.");
scanner.next();
}
}
return value;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double a = readPositiveDouble(scanner, "Enter the length of side A: ");
double b = readPositiveDouble(scanner, "Enter the length of side B: ");
double c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
int decimals = readPositiveInt(scanner, "Enter how many decimal places you want (0 for none): ");
scanner.nextLine();
System.out.print("Enter the unit (e.g., cm, m, inches): ");
String unit = scanner.nextLine();
if (decimals == 0) {
System.out.printf(" The hypotenuse (side c) is: %.0f %s%n", c, unit);
} else {
String format = "%." + decimals + "f %s%n";
System.out.printf(" The hypotenuse (side c) is: " + format, c, unit);
}
scanner.close();
}
}