Java - default option does not fuction in switch - java

hello I wrote a program to convert one temperature from one to another using switch.
the default does not fuction:
When i enter a valid option it works perfectly fine, but when i choose invalid choice it goes the default outputting the lines: You enter invalid choice, please choose again and stop workings without allowing me to choose another choice.
earlier when I tested it, the default allowed me to choose another option.
import java.util.Scanner;
public class Tempature {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
double fahrenheit,celcius,kelvin;
System.out.println("Choose type of temperature:\nf. Fahrenheit\nc. Celcius\nk. Kelvin");
String word = scan.nextLine();
switch(word){
case "f": System.out.println("Enter Fahrenheit temperature: ");
fahrenheit=scan.nextDouble();
celcius = (fahrenheit-32) * 5/9;
kelvin = (fahrenheit + 459.67) * 5/9;
System.out.println("" + celcius + " C");
System.out.println("" + fahrenheit + " F");
System.out.println("" + kelvin + " K");
break;
case "c": System.out.println("Enter the Celcius temperature: ");
celcius=scan.nextDouble();
fahrenheit = (celcius*9)/5 + 32;
kelvin = celcius + 273.15;
System.out.println("" + celcius + " C");
System.out.println("" + fahrenheit + " F");
System.out.println("" + kelvin + " K");
break;
case "k": System.out.println("Enter the Kelvin temperature: ");
kelvin=scan.nextDouble();
fahrenheit = 1.8*(kelvin - 273.15) + 32;
celcius = kelvin - 273.15;
System.out.println("" + celcius + " C");
System.out.println("" + fahrenheit + " F");
System.out.println("" + kelvin + " K");
break;
default: System.out.println("You enter invalid choice, please choose again");
}
scan.close();
}
}

This could help you.
add a while loop and read the input of user in default and it will work.
When user puts q he/she will exit the program.
class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double fahrenheit,celcius,kelvin;
// changed
System.out.println("Choose type of temperature:\nf. Fahrenheit\nc. Celcius\nk. Kelvin\nq. Quit");
String word = scan.next();
//added
while(!word.equals("q")) {
switch(word){
case "f": {
System.out.println("Enter Fahrenheit temperature: ");
fahrenheit=scan.nextDouble();
celcius = (fahrenheit-32) * 5/9;
kelvin = (fahrenheit + 459.67) * 5/9;
System.out.println("" + celcius + " C");
System.out.println("" + fahrenheit + " F");
System.out.println("" + kelvin + " K");
break;
}
case "c":{
System.out.println("Enter the Celcius temperature: ");
celcius=scan.nextDouble();
fahrenheit = (celcius*9)/5 + 32;
kelvin = celcius + 273.15;
System.out.println("" + celcius + " C");
System.out.println("" + fahrenheit + " F");
System.out.println("" + kelvin + " K");
break;
}
case "k": {
System.out.println("Enter the Kelvin temperature: ");
kelvin=scan.nextDouble();
fahrenheit = 1.8*(kelvin - 273.15) + 32;
celcius = kelvin - 273.15;
System.out.println("" + celcius + " C");
System.out.println("" + fahrenheit + " F");
System.out.println("" + kelvin + " K");
break;
}
default: {
System.out.println("You enter invalid choice, please choose again");
// added
System.out.println("Choose type of temperature:\nf. Fahrenheit\nc. Celcius\nk. Kelvin\nq.Quit");
word = scan.next();
break;
}
}// end of swtich
// checking for exit
if(!word.equals("q")) {
System.out.println("Choose type of temperature:\nf. Fahrenheit\nc. Celcius\nk. Kelvin\nq. Quit");
word = scan.next();
}
}// end of while
System.out.println("Exited");
}
}
Output:
Choose type of temperature:
f. Fahrenheit
c. Celcius
k. Kelvin
q. Quit
f
Enter Fahrenheit temperature:
45
7.222222222222222 C
45.0 F
280.3722222222222 K
Choose type of temperature:
f. Fahrenheit
c. Celcius
k. Kelvin
q. Quit
c
Enter the Celcius temperature:
45
45.0 C
113.0 F
318.15 K
Choose type of temperature:
f. Fahrenheit
c. Celcius
k. Kelvin
q. Quit
k
Enter the Kelvin temperature:
45
-228.14999999999998 C
-378.66999999999996 F
45.0 K
Choose type of temperature:
f. Fahrenheit
c. Celcius
k. Kelvin
q. Quit
cdvd
You enter invalid choice, please choose again
Choose type of temperature:
f. Fahrenheit
c. Celcius
k. Kelvin
q.Quit
q
Exited

Related

trouble with logic of 'if-else' or 'switch' statement for temperature conversion

I'm having trouble resolving how to take an input based of two possible options and returning a value for both options.
example:
What temperature system do you use: celsius or Fahrenheit
(after selection is made, in this case celsius, take answer and convert to Fahrenheit)
Output both temperatures
I've tried 'if else' and 'switch' statement but the when I make a selection say Celsius it will convert both
System.out.println("Select which temperature scale you currently use, (c)elsius or (f)ahrenheit: ");
temperatureScale = scannerIn.next();
System.out.println("Temp in C is: " + temperatureInC);
*/
if (temperatureScale.equals("c")) {
System.out.println("Please enter the temperature in Celsius: ");
temperatureInC = scannerIn.nextDouble();
}
else {
System.out.println("Please enter the temperature in Fahrenheit: ");
temperatureInF = scannerIn.nextDouble();
}
tempInCelsiusConvFromFahrenheit = (temperatureInF - 32) * 5/9;
tempInFahrenheitConvFromCelsius = (temperatureInC * 9/5) + 32;
averageQuizScore = ((quiz1 + quiz2 + quiz3)/3);
System.out.println("*** Thank You ***");
System.out.println("Student EMPLID:" + studentID);
System.out.println("Quiz 1 Score: " + quiz1);
System.out.println("Quiz 2 Score: " + quiz2);
System.out.println("Quiz 3 Score: " + quiz3);
System.out.println("Average quiz score: " + df2.format(averageQuizScore));
System.out.println("Age in months: " + age * 12);
System.out.println("Age in years: " + age);
System.out.println("Temperature in Celsius: " + tempInCelsiusConvFromFahrenheit + '°');
System.out.println("Temperature is Fahrenheit: " + tempInFahrenheitConvFromCelsius + '°');
}
}
I selected celsius and enter 32. and thought I would get 32 C and 91.4 but I got:
Temperature in Celsius: -17.77777777777778°
Temperature is Fahrenheit: 91.4°
If you trace your program you will understand:
1) You enter a value for Celcius, therefore your program falls into:
if (temperatureScale.equals("c")) {
System.out.println("Please enter the temperature in Celsius: ");
temperatureInC = scannerIn.nextDouble();
}
then you try display a value for temperature in Celsius by:
System.out.println("Temperature in Celsius: " + tempInCelsiusConvFromFahrenheit + '°');
and you try to do it by getting a value for the tempInCelsiusConvFromFahrenheit
variable.
However, you try to fill tempInCelsiusConvFromFahrenheit variable with a value in
tempInCelsiusConvFromFahrenheit = (temperatureInF - 32) * 5/9;
and you try to get this value in "Else Block" that you never got into:
else {
System.out.println("Please enter the temperature in Fahrenheit: ");
temperatureInF = scannerIn.nextDouble();
}
but you never get into there. So it is probably initialized as 0 when you declare it. And (0-32)*5/9 = -17.78°C. So the output is correct.
But your coding design is wrong.
I hope this helps.
Your calculations are correct. If the user inputs celsius don't convert it. In other words temp in celsius is tempuratureInC and not tempInCelsiusConvFromFahrenheit.

calcAverage issue

I don't know why my code is not calculating the average. It is compiling and running, but gives 0% as average. Here are the instructions for the assignment
Average and Grade (Methods Program):
Write a program that asks the user to enter 5 test scores. Your program should then display a letter
grade for each test score, the average test score and the overall letter grade
for the average score. You can NOT use a for loop or an array (we haven't even covered that) in this
program - the point is to learn how to define methods and call them several
times if necessary.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Homework8{
static double average;
static char grade;
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
char letter1;
char letter2;
char letter3;
char letter4;
char letter5;
double score1;
double score2;
double score3;
double score4;
double score5;
double score;
System.out.println("Please enter the first score between 0 and 100: ");
score1 = keyboard.nextDouble();
System.out.println("Please enter the second score between 0 and 100: ");
score2 = keyboard.nextDouble();
System.out.println("Please enter the third score between 0 and 100: ");
score3 = keyboard.nextDouble();
System.out.println("Please enter the fourth score between 0 and 100: ");
score4 = keyboard.nextDouble();
System.out.println("Please enter the fifth score between 0 and 100: ");
score5 = keyboard.nextDouble();
//System.out.println("The average of your five tests was: " +
System.out.println(
"For TestA you scored: " + score1 + " giving you Grade: "
+ determineGrade(score1)
+ "\nFor TestB you scored: " + score2 + " giving you Grade: "
+ determineGrade(score2)
+ "\nFor TestC you scored: " + score3 + " giving you Grade: "
+ determineGrade(score3)
+ "\nFor TestD you scored: " + score4 + " giving you Grade: "
+ determineGrade(score4)
+ "\nFor TestF you scored: " + score5 + " giving you Grade: "
+ determineGrade(score5)
+ "\nBased on your average: " + average + " Your final Grade is: "
+ determineGrade((double)average));
}
public static double calcAverage(double score1, double score2, double score3, double score4, double score5) {
double average = (score1+score2+score3+score4+score5) / 5;
return average;
}
public static char determineGrade(double score)
{
if(score<=100 && score>=90)
{
return 'A';
}
else if(score>=80)
{
return 'B';
}
else if(score>=70)
{
return 'C';
}
else if(score>=60)
{
return 'D';
}
else
{
return 'F';
}
}
}
you define the method calcAverage but you didn't call it.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Homework8{
static double average;
static char grade;
public static void main (String[] args) {
Scanner keyboard = new Scanner(System.in);
char letter1;
char letter2;
char letter3;
char letter4;
char letter5;
double score1;
double score2;
double score3;
double score4;
double score5;
double score;
System.out.println("Please enter the first score between 0 and 100: ");
score1 = keyboard.nextDouble();
System.out.println("Please enter the second score between 0 and 100: ");
score2 = keyboard.nextDouble();
System.out.println("Please enter the third score between 0 and 100: ");
score3 = keyboard.nextDouble();
System.out.println("Please enter the fourth score between 0 and 100: ");
score4 = keyboard.nextDouble();
System.out.println("Please enter the fifth score between 0 and 100: ");
score5 = keyboard.nextDouble();
double average = calcAverage(score1,score2,score3,score4,score5);
//System.out.println("The average of your five tests was: " +
System.out.println(
"For TestA you scored: " + score1 + " giving you Grade: "
+ determineGrade(score1)
+ "\nFor TestB you scored: " + score2 + " giving you Grade: "
+ determineGrade(score2)
+ "\nFor TestC you scored: " + score3 + " giving you Grade: "
+ determineGrade(score3)
+ "\nFor TestD you scored: " + score4 + " giving you Grade: "
+ determineGrade(score4)
+ "\nFor TestF you scored: " + score5 + " giving you Grade: "
+ determineGrade(score5)
+ "\nBased on your average: " + average + " Your final Grade is: "
+ determineGrade((double)average));
}
public static double calcAverage(double score1, double score2, double score3, double score4, double score5) {
double average = (score1+score2+score3+score4+score5) / 5.0;
return average;
}
public static char determineGrade(double score)
{
if(score<=100 && score>=90)
{
return 'A';
}
else if(score>=80)
{
return 'B';
}
else if(score>=70)
{
return 'C';
}
else if(score>=60)
{
return 'D';
}
else
{
return 'F';
}
}
}

output formatting Java

my question is simple, how can i get my output to format two values with two decimal places. for whatever reason i cant output the "current balance" & "new balance" with two decimal places. separately they work fine but when together i get a conversion error. is this a rule i'm unaware of? i would like do do this with one action if possible. this is simply a cosmetic issue and all operations perform fine when i take out the formatting.
thanks,
public static void main(String[] args)
{
double min;
int accNum;
char accType;
double bal;
double newBal;
//user inputs
System.out.println("Please enter your account number: ");
accNum = console.nextInt();
System.out.println();
System.out.println("Enter the account type: s(savings) or c(checking)");
accType = console.next().charAt(0);
System.out.println();
//savings v checking
switch (accType)
{
case 's':
case 'S':
System.out.println("Enter the current balance: ");
bal = console.nextDouble();
System.out.println("Enter the minimum balance: ");
min = console.nextDouble();
System.out.println();
if (bal < min)
{
newBal = bal - S_MIN_FEE;
System.out.println("Insufficient Funds (-$10.00)");
}
else
newBal = bal + (bal * S_INT);
System.out.printf("Account #: " + accNum + "\n"
+ "Account Type: Savings" + "\n" + "Current Balance: "
+ "$%.2f%n", bal + "New Balance: $%.2f", newBal);
case 'c':
case 'C':
System.out.println("Enter the current balance: ");
bal = console.nextDouble();
System.out.println("Enter the minimum balance: ");
min = console.nextDouble();
System.out.println();
if (bal < min)
{
newBal = bal - C_MIN_FEE;
System.out.println("Insufficent Funds (-$25.00)");
}
else if (bal < C_BAL_MAX && bal >= min)
newBal = bal + (bal * C_INT);
else
newBal = bal + (bal * C_INT_MAX);
System.out.printf("Account #: " + accNum + "\n"
+ "Account Type: Checking" + "\n" + "Current Balance: "
+ "$%.2f%n", bal + "New Balance: $%.2f%n", newBal);
That is because you put the format first, and only first.
System.out.printf("%.2f %.2f%n", bal, newBal);
This is the same problem/mistake as posted an hour ago. java.util.IllegalFormatConversionException: f != java.lang.String Error

Cannot get a java variable to print

I cannot get the variable adjustedCharge to print out (the text is printed but not the value) I have tried to trace but still cannot get it to print properly. No errors are present either.
import java.util.Scanner;
public class Assignment {
public static void main(String[] args) {
//Declare scanner
Scanner input = new Scanner(System.in);
//Prompt for information
System.out.print("Customer's name:");
String name = input.nextLine();
System.out.print("Customer's address:");
String address = input.nextLine();
System.out.print("Customer's phone number:");
String phone = input.nextLine();
System.out.print("Customer's licence number:");
String licence = input.nextLine();
System.out.print("Customer's credit card number:");
String ccard = input.nextLine();
System.out.print("Credit card expiry date (MM/YYYY):");
String expiry = input.nextLine();
System.out.print("Hire length (in days):");
int hire = Integer.parseInt(input.nextLine());
System.out.print("Make/Model:");
String model = input.nextLine();
System.out.print("Registration of car:");
String rego = input.nextLine();
System.out.print("Hire rate (per day) Either S, M, L:");
char inputRate = input.nextLine().charAt(0);
System.out.print("Total days hired out:");
int totalDays = Integer.parseInt(input.nextLine());
//
double dtotalDays = totalDays;
double surcharge = dtotalDays - hire;
//Daily hire rate / Stage 2
double rate = 0;
if (inputRate == 'S' || inputRate == 's'){
rate = (char) 80.0;
}
if (inputRate == 'M' || inputRate == 'm'){
rate= 110.0;
}
if (inputRate == 'L' || inputRate == 'l'){
rate= 140.0;
}
//Calculate late fees
double penalty = rate * (surcharge * 2);
//Start Stage 3
double dCost=0;
double tCost=0;
StringBuilder dDetail = new StringBuilder("The damage Details are:" + "\n");
StringBuilder tDetail = new StringBuilder("The traffic fines are:" + "\n");
//Setup an exit statement
boolean quit = false;
while (!quit){
System.out.println("<<<Enter one of the following commands:>>>");
System.out.println("A - Damage Repair");
System.out.println("B - Traffic Infringement");
System.out.println("X - Exit Menu");
String schoiceEntry = input.next();
char choiceEntry = schoiceEntry.charAt(0);
//Integer.parseInt(input.nextLine());
double damageCost = 0;
switch (choiceEntry){
case 'A':
case 'a':
input.nextLine();
System.out.println("Enter a description of the damage:");
String damageDetail = input.nextLine();
System.out.println("Enter the damage cost:");
damageCost = input.nextInt();
System.out.print("The damage is: " + damageDetail + "\n");
System.out.print("The damage cost is: " + "$" + damageCost + "\n");
dDetail.append("-" + damageDetail + "\n");
dCost = dCost + damageCost;
System.out.println("----------------------------------");
break;
case 'B':
case 'b':
input.nextLine();
System.out.print("Enter a description of the traffic infringement:");
String trafficDetail = input.nextLine();
System.out.println("Enter the traffic infringement cost:");
double trafficCost = Integer.parseInt(input.nextLine());
tDetail.append("-" + trafficDetail + "\n");
tCost = tCost + trafficCost;
System.out.println("----------------------------------");
break;
case 'X':
case 'x':
quit = true;
System.out.print("***Menu entry has been terminated***" + "\n");
//System.out.printf("Total traffic cost is: %75s\n", "$" + tCost + "\n");
//System.out.printf("Total Damage cost is: %77s\n", "$" + dCost + "\n");
//System.out.printf(tDetail + "\n");
//System.out.print(dDetail + "\n");
break;
default:
System.out.print("Please enter either a valid menu selection (A, B, or X):" + "\n");
break;
}
}
double dhire = hire;
double charge = dhire*rate;
double adjustedCharge = charge + penalty;
//Print summary
System.out.println("---------------------------------------------"+
"------------------------------------------------------\n" +
"***CUSTOMER DETAILS:***\n");
System.out.printf("Name: %93s\n", name);
System.out.printf("Address: %90s\n", address);
System.out.printf("Phone Number: %85s\n", phone);
System.out.printf("Licence Number: %83s\n", licence);
System.out.printf("Credit Card Number: %79s\n", ccard);
System.out.printf("Credit Card Expiry: %79s\n", expiry);
System.out.println( "\n***CAR HIRE DETAILS:***\n");
System.out.printf("Make/Model: %87s\n", model);
System.out.printf("Registration Number: %78s\n", rego);
System.out.printf("Hire Length (days): %79s\n", model);
System.out.printf("Daily Hire Rate: %82s\n", rate);
System.out.printf("Basic Hire Charge: %80s\n\n", charge);
System.out.printf("Days hired: %87s\n", totalDays);
if (totalDays == hire){
System.out.printf("Late Return Surcharge: %76s\n", "$0.00");
}
if (totalDays > hire){
System.out.printf("Late Return Surcharge: %76s\n", + penalty);
}
System.out.printf("Adjusted Hire Charge: %77s\n", "\n", "$" + adjustedCharge + "\n");
System.out.print(dDetail + "\n");
System.out.printf("Total damage cost is: %78" + "s\n", "$" + dCost + "\n");
System.out.printf(tDetail + "\n");
System.out.printf("Total traffic fines incurred: %70s\n", "$" + tCost + "\n");
System.out.printf("Final hire charge: %79s\n", "$" + (adjustedCharge + dCost + tCost));
}
}
I just changed the way you printed out the adjustedCharge so you can still use printf
System.out.printf("Adjusted Hire Charge: %77s","$");
System.out.printf("%.1f",adjustedCharge);
System.out.printf("\n");
With printf you need to format the value you're printing and in this case, because you're trying to print a double, you'll need to format it with %f
I also noticed that my previous answer messed up the spacing you had for the rest of your output. So here's the fixed solution! Just change up the spacing to however you'd like
Or you can
use
Pass two arguments to printf
System.out.printf("Adjusted Hire Charge: %77s\n", "$" + adjustedCharge + "\n")
instead of
System.out.printf("Adjusted Hire Charge: %77s\n", "\n", "$" + adjustedCharge + "\n");

Not sure what loop to use

Edit: Just wanted to say thank you to everyone who've helped so far! I'm new to Java and my professor recommended this site for outside help. It's been great so far. I'm going to take a few moments and work on the code and implement the suggestions I've received. Thanks!
I'm trying to create a program that converts temperatures from degrees Fahrenheit to degrees Celsius, and vice-versa. If the user does not enter the correct unit, the program loops back and asks them to re-enter the unit or enter Q to quit the program. This is what I have so far:
My thinking is to incorporate a loop into the default portion of my switch statement, but I'm not sure which loop to use (maybe for?) that will loop back and ask the user to re enter the unit or Q to quit. Any help is really, really appreciated! I've been stuck on this for hours!
System.out.print("\tEnter 'F' (or 'f') for Fahrenheit or "
+ "'C' (or 'c') for Celcius: ");
f_or_c = console.next();
double fahrenheit = 5*(temperature-32)/9;
double celcius = (9*(temperature)/5)+32;
switch (f_or_c) {
case "C":
case "c":
System.out.println("\n\t" + temperature + " " + " degrees Celcius "
+ "= " + celcius + " degrees Fahrenheit.");
break;
case "F":
case "f":
System.out.println("\n\t" + temperature + " " + " degrees Fahrenheit "
+ "= " + fahrenheit + " degrees Celcius.");
break;
default:
System.out.println("\n\tUnknown units -"
+ "\n\tCannot do calculation -"
+ "\n\tPlease next time enter either 'F' for Fahrenheit or 'C' Celcius");
System.out.print("\nEnter 'Q' to quit or " +
"any other character to perform another temperature conversion: ");
break;
Let's think this through logically: you want to loop until the user enters the correct input. So, does this mean that you will know prior to starting the loop how many times the loop should iterate? This is key.
Once you know this information, the correct loop falls out, since:
for loops are used when you know in advance how many times you'll loop.
While loops are for when you don't know this information in advance.
You can go with while loop. There are better ways to do this. But just helping you with your code.
System.out.print("\tEnter 'F' (or 'f') for Fahrenheit or "
+ "'C' (or 'c') for Celcius: ");
f_or_c = console.next();
boolean flag=false;
double fahrenheit = 5*(temperature-32)/9;
double celcius = (9*(temperature)/5)+32;
while(true) {
switch (f_or_c) {
case "C":
case "c":
System.out.println("\n\t" + temperature + " " + " degrees Celcius "
+ "= " + celcius + " degrees Fahrenheit.");
flag=false;
break;
case "F":
case "f":
System.out.println("\n\t" + temperature + " " + " degrees Fahrenheit "
+ "= " + fahrenheit + " degrees Celcius.");
flag=false;
break;
default:
System.out.println("\n\tUnknown units -"
+ "\n\tCannot do calculation -"
+ "\n\tPlease next time enter either 'F' for Fahrenheit or 'C' Celcius");
System.out.print("\nEnter 'Q' to quit or " +
"any other character to perform another temperature conversion: ");
flag=true;
break;
}
if(flag)
continue;
break;
}
Put the switch statement into a method, and then call that method upon itself for the default case. It's using recursion, but keep in mind if you use recursion in the future, make sure it doesn't infinitely loop or you'll get a stack overflow error.
I might be changing your way of thinking here, but I would Implement it differently. Wrap a while loop around the switch case. This will make sure the switch case is re-executed with the next user input value. I've included an example of what it could look like. Note that I haven't included the input code as there are many options for you. Also, I haven't included the quit code, it only breaks the loop.
bool repeat = TRUE;
while (repeat)
{
switch (f_or_c)
{
case "C":
case "c":
System.out.println("\n\t" + temperature + " " + " degrees Celcius "
+ "= " + celcius + " degrees Fahrenheit.");
repeat = FALSE;
break;
case "F":
case "f":
System.out.println("\n\t" + temperature + " " + " degrees Fahrenheit "
+ "= " + fahrenheit + " degrees Celcius.");
repeat = FALSE;
break;
case "Q":
***YOUR CODE TO QUIT***
repeat = FALSE;
break;
default:
System.out.println("\n\tUnknown units -"
+ "\n\tCannot do calculation -"
+ "\n\tPlease next time enter either 'F' for Fahrenheit or 'C' Celcius");
System.out.print("\nEnter 'Q' to quit or " +
"any other character to perform another temperature conversion: ");
***CODE TO PROMPT USER FOR F_OR_C VALUE***
repeat = TRUE;
break;
}
}
How about a do{}while()?
boolean badInput;
do {
badInput = false;
System.out.print("\tEnter 'F' (or 'f') for Fahrenheit or "
+ "'C' (or 'c') for Celcius: ");
f_or_c = console.next();
double fahrenheit = 5*(temperature-32)/9;
double celcius = (9*(temperature)/5)+32;
switch (f_or_c) {
case "C":
case "c":
System.out.println("\n\t" + temperature + " " + " degrees Celcius "
+ "= " + celcius + " degrees Fahrenheit.");
break;
case "F":
case "f":
System.out.println("\n\t" + temperature + " " + " degrees Fahrenheit "
+ "= " + fahrenheit + " degrees Celcius.");
break;
default:
System.out.println("\n\tUnknown units -"
+ "\n\tCannot do calculation -"
+ "\n\tPlease next time enter either 'F' for Fahrenheit or 'C' Celcius");
System.out.print("\nEnter 'Q' to quit or " +
"any other character to perform another temperature conversion: ");
badInput = true; //we got bad input so we'll continue looping
break;
} while(badInput);
Essentially we set badInput to false at the beginning, assuming it to be good input. If we end up getting bad input, we make badInput true, so we will continue looping.
The general difference between a do-while and a while loop is that do-whiles are used for code that you want to execute at least once. It works well in this case, because you know you want to read input at least once.
In my example, the variable badInput is called a flag. Basically, a flag is just a variable that tracks whether something is "on" or "off". In this case, badInput is tracking whether or not we have bad input. Its a simple "on" "off", "true" "false" scenario.

Categories

Resources