-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTemperatureConverter.java
More file actions
77 lines (64 loc) · 2.08 KB
/
TemperatureConverter.java
File metadata and controls
77 lines (64 loc) · 2.08 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
68
69
70
71
72
73
74
75
76
77
/**
* Logan Morris
* 30 May 2022
* Simple temperature converter program with user input and conversions
*/
import java.util.Scanner;
public class TemperatureConverter {
public static void main(String[] args) {
// Initial welcome message
Scanner myObj = new Scanner(System.in);
System.out.println("Welcome to the temperature converter! Enter a " +
"temperature in either Fahrenheit or Celsius: ");
String temperature = myObj.nextLine();
// User input validation for the unit
String unit = "";
boolean done = false;
while (!done) {
System.out.println("Is this F or C?");
unit = myObj.nextLine();
if (unit.toLowerCase().equals("c") ||
unit.toLowerCase().equals("f")) {
done = true;
}
else {
System.out.println("The only values you can enter are C or F, " +
"please try again");
}
}
myObj.close();
// Initial print
System.out.println("The temperature you entered was: " + temperature +
" degrees " + unit);
float conv_temp = convert_degrees(unit, temperature);
// Print statement for Fahrenheit conversion
if (unit.toLowerCase().equals("c")) {
System.out.println("The converted temperature is: " + conv_temp +
" degrees F");
}
// Print statement for Celsius conversion
else {
System.out.println("The converted temperature is: " + conv_temp +
" degrees C");
}
}
/**
* Unit conversion method; takes a string input, converts it to an int
* and performs the necessary unit conversion
* @param unit the unit the user inputted
* @param temp the temp the user inputted
* @return the newly converted temperature as a string for output
*/
private static float convert_degrees(String unit, String temp) {
float conv_temp = 0;
// Conversion for F to C
if (unit.toLowerCase().equals("f")) {
conv_temp = (Float.parseFloat(temp) - 32) * 5 / 9;
}
// Conversion for C to F
else {
conv_temp = Float.parseFloat(temp) * 9 / 5 + 32;
}
return conv_temp;
}
}