Created
March 6, 2024 11:55
-
-
Save ajeetraina/c781327440331c4ba82e881fe9128d5b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class TemperatureConverter { | |
public static void main(String[] args) { | |
Scanner scanner = new Scanner(System.in); | |
int choice; | |
do { | |
displayMenu(); | |
choice = getChoice(scanner); | |
if (choice != 3) { | |
double temperature = getTemperature(scanner); | |
calculateAndDisplayTemperature(temperature, choice); | |
} | |
} while (choice != 3); | |
System.out.println("Exiting program..."); | |
scanner.close(); | |
} | |
public static void displayMenu() { | |
System.out.println("\nTemperature Converter"); | |
System.out.println("1. Convert Fahrenheit to Celsius"); | |
System.out.println("2. Convert Celsius to Fahrenheit"); | |
System.out.println("3. Exit"); | |
} | |
public static int getChoice(Scanner scanner) { | |
System.out.print("Enter your choice (1-3): "); | |
while (!scanner.hasNextInt()) { | |
System.out.println("Invalid input. Please enter a number between 1 and 3."); | |
scanner.next(); | |
} | |
return scanner.nextInt(); | |
} | |
public static double getTemperature(Scanner scanner) { | |
System.out.print("Enter temperature: "); | |
while (!scanner.hasNextDouble()) { | |
System.out.println("Invalid input. Please enter a number."); | |
scanner.next(); | |
} | |
return scanner.nextDouble(); | |
} | |
public static void calculateAndDisplayTemperature(double temperature, int choice) { | |
double convertedTemperature; | |
if (choice == 1) { | |
convertedTemperature = (temperature - 32) * 5 / 9.0; | |
System.out.printf("%.2f Fahrenheit is equal to %.2f Celsius\n", temperature, convertedTemperature); | |
} else { | |
convertedTemperature = (temperature * 9 / 5.0) + 32; | |
System.out.printf("%.2f Celsius is equal to %.2f Fahrenheit\n", temperature, convertedTemperature); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment