The following is a program that I wrote which converts Celsius Temperature to Fahrenheit and vice versa. Everything in the program works EXCEPT the default for the switch statement.
If the user were to press any number except 1 or 2, then the default statement should notify the user to re-enter the correct number. Instead, the program just skips the default statement and re-prints "Please enter 1 for Celsius and 2 for Fahrenheit. To exit the program, enter 0."
Here is how the program output looks when I run it:
/*
Which temperature would you like to convert?
Please enter 1 for Celsius and 2 for Fahrenheit. To exit the program, enter 0.
1.Celsius
2.Fahrenheit
Your entry: 1
Please enter Celsius temperature: 34
The temperature you entered, 34.0 degrees in Celsius, is 93.20 degrees in Fahrenheit.
Please enter 1 for Celsius and 2 for Fahrenheit. To exit the program, enter 0.
1.Celsius
2.Fahrenheit
Your entry: 5
Please enter 1 for Celsius and 2 for Fahrenheit. To exit the program, enter 0. Here is where the program should print: "In-correct degree type entered. Choose 1 or 2 please," but it does not print.
1.Celsius
2.Fahrenheit
Your entry: 0
Program is closed.
*/
Here is my coding:
import java.util.Scanner; public class Temperature { public static void main(String [] args) { Scanner input = new Scanner(System.in);//create object from Scanner class named input int counter = 0; int degreetype = 0; System.out.print("Which temperature would you like to convert?"); do { System.out.print("\n\nPlease enter 1 for Celsius and 2 for Fahrenheit. To exit the program, enter 0. \n\n1.Celsius \n2.Fahrenheit"); System.out.print("\n\nYour entry: "); degreetype = input.nextInt(); if (degreetype<=2 && degreetype!=0) { switch(degreetype) { case 1: double celsius = 0.0; System.out.print("\nPlease enter Celsius temperature: "); celsius = input.nextDouble(); tempCel(celsius); break; case 2: double fahrenheit = 0.0; System.out.print("\nPlease enter Fahrenheit temperature: "); fahrenheit = input.nextDouble(); tempFar(fahrenheit); break; default: System.out.println("\nIn-correct degree type entered. Choose 1 or 2 please."); break;[B]//This line does not print if user enters any number other than 1 or 2. I do not know why it does not print. [/B] } } } while(degreetype!=0); System.out.println("\nProgram is closed."); } public static void tempFar(double fahrenheit) { double celsius = 0.00; celsius = 5.0 / 9.0 * (fahrenheit - 32); System.out.printf("\nThe temperature you entered, "+ fahrenheit +" degrees in Fahereheit, is %.2f degrees in Celsius.", celsius); } public static void tempCel(double celsius) { double fahrenheit = 0.00; fahrenheit = 9.0/5.0 * celsius + 32; System.out.printf("\nThe temperature you entered, "+ celsius +" degrees in Celsius, is %.2f degrees in Fahrenheit.", fahrenheit); } }//close class