|
-
January 3rd, 2012, 03:08 PM
#3
Re: Having trouble building this converter without using goto
You're on the right track, Jim Using a single loop control variable like 'finished' is good programming practice. I applied the same principle to the nested loops contained within the case structure as well.
Code:
using System;
namespace CSharp_Lesson_1_4_Practice
{
public static class Program
{
public static void Main()
{
// The purpose of this program is to create a temperature converter from Celius to Fareinheit and vice versa.
bool exitMain = false;
do
{
string inputTempStr;
string optionStr;
int optionInt;
float fTemp;
float cTemp;
bool exitConvert = false;
Console.WriteLine("This program converts temperatures between Celsius and Fahrenheit.\n");
Console.WriteLine("Which do you want to convert:");
Console.WriteLine("1. Celsius to Fahrenheit");
Console.WriteLine("2. Fahrenheit to Celsius");
Console.WriteLine("0. Exit\n");
Console.Write("Enter 0, 1 or 2 for your choice: ");
optionStr = Console.ReadLine();
optionInt = Int32.Parse(optionStr);
switch (optionInt)
{
case 0:
exitMain = true;
break;
case 1:
do
{
string eval;
// ask for user to input Celsius temperature
Console.Write("Enter the temperature in Celsius so I can convert it to Fahrenheit for you: ");
inputTempStr = Console.ReadLine();
cTemp = Single.Parse(inputTempStr);
// calculate Fahrenheit value
fTemp = ((cTemp * 1.8F) + 32.0F);
Console.Write("The temperature from Celsius to Fahrenheit is: {0}\n", fTemp);
// see if user wants to perform another Celsius to Fahrenheit conversion
Console.Write("Do you want to continue? (yes/no): ");
eval = Console.ReadLine();
if (eval.ToLower().Equals("no"))
{
exitConvert = true; // no? set convert loop control variable to false
}
}
while (!exitConvert); // exit temp conversion loop?
break;
case 2:
do
{
string eval;
// ask for user to input Celsius temperature
Console.Write("Enter the temperature in Fahrenheit so I can convert it to Celsius for you: ");
inputTempStr = Console.ReadLine();
fTemp = Single.Parse(inputTempStr);
// calculate Fahrenheit value
cTemp = ((fTemp - 32.0F) / 1.8F);
Console.Write("The temperature from Fahrenheit to Celsius is: {0}\n", cTemp);
// see if user wants to perform another Celsius to Fahrenheit conversion
Console.Write("Do you want to continue? (yes/no): ");
eval = Console.ReadLine();
if (eval.ToLower().Equals("no"))
{
exitConvert = true; // no? set convert loop control variable to false
}
}
while (!exitConvert); // exit temp conversion loop?
break;
}
}
while (!exitMain);
Console.WriteLine("Goodbye!!!");
Console.ReadLine();
}
}
}
R.I.P. 3.5" Floppy Drives
"I know not with what weapons World War III will be fought, but World War IV will be fought with sticks and stones." - Albert Einstein
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|