This repository was archived by the owner on Jun 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathTemperatureConverter.java
More file actions
86 lines (73 loc) · 2.91 KB
/
TemperatureConverter.java
File metadata and controls
86 lines (73 loc) · 2.91 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
78
79
80
81
82
83
84
85
86
import java.util.Scanner;
public class TemperatureConverter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Temperature Converter");
System.out.println("Choose the original temperature scale:");
System.out.println("1. Celsius");
System.out.println("2. Fahrenheit");
System.out.println("3. Kelvin");
int originalScale = scanner.nextInt();
System.out.println("Enter the temperature:");
double temperature = scanner.nextDouble();
System.out.println("Choose the target temperature scale:");
System.out.println("1.Celsius");
System.out.println("2.Fahrenheit");
System.out.println("3.Kelvin");
int targetScale = scanner.nextInt();
double convertedTemperature = convertTemperature(temperature, originalScale, targetScale);
System.out.println("Converted temperature:" + convertedTemperature);
scanner.close();
}
public static double convertTemperature(double temperature, int originalScale, int targetScale) {
switch (originalScale) {
case 1:
switch (targetScale) {
case 1:
return temperature;
case 2:
return celsiusToFahrenheit(temperature);
case 3: // Celsius to Kelvin
return celsiusToKelvin(temperature);
}
case 2:
switch (targetScale) {
case 1:
return fahrenheitToCelsius(temperature);
case 2:
return temperature;
case 3:
return fahrenheitToKelvin(temperature);
}
case 3: // Kelvin
switch (targetScale) {
case 1:
return kelvinToCelsius(temperature);
case 2:
return kelvinToFahrenheit(temperature);
case 3:
return temperature;
}
default:
return 0.0;
}
}
public static double celsiusToFahrenheit(double celsius) {
return (celsius * 9 / 5) + 32;
}
public static double celsiusToKelvin(double celsius) {
return celsius + 273.15;
}
public static double fahrenheitToCelsius(double fahrenheit) {
return (fahrenheit - 32) * 5 / 9;
}
public static double fahrenheitToKelvin(double fahrenheit) {
return (fahrenheit + 459.67) * 5 / 9;
}
public static double kelvinToCelsius(double kelvin) {
return kelvin - 273.15;
}
public static double kelvinToFahrenheit(double kelvin) {
return (kelvin * 9 / 5) - 459.67;
}
}