I made a program that calculates the temperature in different ways.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Excercise_7
{
class Program
{
static void Main(string[] args)
{
showBegin();
decide();
secondPlay();
showEnd();
}
// Decide code
static void decide() {
int choice;
string input;
input = Console.ReadLine();
int.TryParse(input, out choice);
if (choice == 1)
{
Console.WriteLine("");
celciusSystem();
}
else if (choice == 2)
{
Console.WriteLine("");
farenheitSystem();
}
else if (choice == 3)
{
Console.WriteLine("");
kelvinSystem();
}
else {
Console.WriteLine("");
Console.WriteLine("Make sure u write a number between 1 and 3! No text!");
Console.WriteLine("");
showBegin();
decide();
}
}
static void secondPlay()
{
int choice2;
string input;
Console.WriteLine("");
Console.WriteLine("Type 1 to play again, type 2 to close the application");
input = Console.ReadLine();
int.TryParse(input, out choice2);
}
// Begin code
static void showBegin()
{
Console.WriteLine("Welcom at the temperature calculator, pick the mode u prefer!");
Console.WriteLine("Press 1 for Celcius mode");
Console.WriteLine("Press 2 for Fahrenheit mode");
Console.WriteLine("Press 3 for Kelvin mode");
Console.WriteLine("Press the correct number and then hit the enter button!");
Console.WriteLine("");
}
// Temperature Calculators
static void celciusSystem()
{
Console.WriteLine("This is the Celsius calculator");
Console.Write("Enter the amount of celsius: ");
int celsius = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
Console.WriteLine("The temperature in Kelvin = {0}", celsius + 273);
Console.WriteLine("The temperature in Fahrenheit = {0}", celsius * 18 / 10 + 32);
}
static void farenheitSystem()
{
Console.WriteLine("This is the Fahrenheit calculator");
Console.Write("Enter the amount of Fahrenheit: ");
int Fahrenheit = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
Console.WriteLine("The temperature in Kelvin = {0}", (Fahrenheit + 459.67) / 1.8);
Console.WriteLine("The temperature in Celsius = {0}", (Fahrenheit - 32) / 1.8);
}
static void kelvinSystem()
{
Console.WriteLine("This is the Kelvin calculator");
Console.Write("Enter the amount of Kelvin: ");
int Kelvin = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
Console.WriteLine("The temperature in Fahrenheit = {0}", Kelvin * 1.8 - 459.67);
Console.WriteLine("The temperature in Celsius = {0}", Kelvin - 273.15);
}
// End code
static void showEnd()
{
Console.WriteLine("");
Console.WriteLine("We hoped u enjoyed our application!");
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
}
}
}
So now my question, I made a class called second play. Within that class i tried to make a kind a statement that would ask the user if he or she wanted to "play" again. So if they write 1 he should loop the game again.
I have tried it with this
if (choice2 == 1)
{
while (choice2 == 1) {
Console.WriteLine("");
showBegin();
decide();
}
}
else {
Console.WriteLine("");
Console.WriteLine("Cheers!!");
}
}
then he actually worked but not the way I wanted to because if the user writes 1 it will loop the first thing all over again. So the user can't quit the game any more.
I want the application to ask after every trail if he or she wants to play again by typing 1 or 2.
You already know how to read lines from the console, you also know how to use if to compare booleans, so why don't you just apply this and check if they wrote a 1 or 2?
private bool playAgain()
{
int number = 2; //Invalid option: close game
Int32.TryParse(Console.ReadLine(), out number);
if (number == 1)
{
return true;
}
else if (number == 2)
{
return false;
}
else
{
Console.WriteLine("Unknown option, quitting!");
return false;
}
}
Then you just have to use that function to determine if they want to play again in a do-loop.
static void Main(string[] args)
{
showBegin(); //Show begin sequence
do
{
decide();
secondPlay();
} while(playAgain()); //Play again if they want to
showEnd(); //Show end sequence when they decided not to play
}
Pro tip: use a switch-case statement instead of multiple if-else statements.
You can use a do while loop, which serves you well in cases like yours, when you want to execute your loop at least once:
do {
Console.WriteLine("");
showBegin();
decide();
//Ask for choice2 here
}
while(choice2 == 1);
Console.WriteLine("");
Console.WriteLine("Cheers!!");
To enter game loop, it is most useful to start with simple while or do-while.
while( conditionToRun )
{
//run the program
if( userWantToExit )
conditionToRun = false;
}
Or
do
{
// run the program
} while ( !userWantToExit )
This code shows the most basic stuff to handle this.
To apply on Your game/program, use:
static void Main(string[] args)
{
bool userWantToEnd = false;
showBegin();
while( !userWantToEnd)
{
decide();
userWantToEnd = IsUserWillingToContinue();
}
showEnd();
}
And adjust the SecondPlay() method into something like IsUserWillingToContinue():
public bool IsUserWillingToContinue()
{
int choice2;
string input;
Console.WriteLine("");
Console.WriteLine("Type 1 to play again, type 2 to close the application");
input = Console.ReadLine();
int.TryParse(input, out choice2);
return choice2 == 1;
}
Adding more info based on comment of #devRicher - You should split up a bit the code so it work in this way
bool runAgain = true;
Console.WriteLine("Begin info: (Hello this is XY game.)");
while(runAgain)
{
Console.WriteLine("You have 3 options: 1, 2, 3");
PickOptionAndRunTheCode();
bool runAgain = DoYouWantToContinue();
Console.Clear(); // clear the Console screen (next time You will see only options, not the text on first run).
}
I would recommend to get more knowledge about games to go to this page -> http://gameprogrammingpatterns.com/ (and read the book)
Check this pattern: Game Loop
Related
I'm trying to restart my program after I catch an error using the catch() function, but I also want it to display the error, stop the rest of the program from running, and restart the program.
This is just a shortened version of my code which I have used as an example.
using System;
namespace Calculator
{
internal class Program
{
private static void Main(string[] args)
{
float input = 0;
while (input != 5)
{
Console.Clear();
Console.WriteLine("What would you like to do? Type: 1 for Addition. Write 5 to end program.");
try
{
input = float.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
}
//Addition
if (input == 1)
{
Console.WriteLine("Enter First Value: ");
string FirstValue = Console.ReadLine();
float firstval = 0;
try
{
firstval = float.Parse(FirstValue);
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
break;
}
Console.WriteLine("Enter Second Value: ");
string SecondValue = Console.ReadLine();
float secval = 0;
try
{
secval = float.Parse(SecondValue);
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
break;
}
float sum = Add(firstval, secval);
Console.WriteLine("The sum is: {0}", sum);
}
}
}
public static float Add(float num1, float num2)
{
return num1 + num2;
}
}
}
When it says
catch (FormatException)
{
Console.WriteLine("Please enter a number");
break;
}
The break; makes it so the rest of the code stops, and it displays the error. That is good, but the program also ends after that, what I want, is that the program repeats after error. Is there any way that this could happen, but it allows 1) the Console.WriteLine("Please enter a number");, 2) the program to not run the rest of the code (The part where we are asked for a second value), and 3) the program to restart for the beginning. Please let me know if that didn't make sense, as it was a hard to explain. :)
It is very simple you do not need the "break" keyword because "break" terminates the loop execution to continue execution on exception use "continue" keyword without quotes the working fiddle is here
and your code after replacing "break" with "continue" is following
using System;
namespace Calculator
{
public class Program
{
public static void Main(string[] args)
{
float input = 0;
while (input != 5)
{
Console.Clear();
Console.WriteLine("What would you like to do? Type: 1 for Addition. Write 5 to end program.");
try
{
input = float.Parse(Console.ReadLine());
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
}
//Addition
if (input == 1)
{
Console.WriteLine("Enter First Value: ");
string FirstValue = Console.ReadLine();
float firstval = 0;
try
{
firstval = float.Parse(FirstValue);
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
continue;
}
Console.WriteLine("Enter Second Value: ");
string SecondValue = Console.ReadLine();
float secval = 0;
try
{
secval = float.Parse(SecondValue);
}
catch (FormatException)
{
Console.WriteLine("Please enter a number");
continue;
}
float sum = Add(firstval, secval);
Console.WriteLine("The sum is: {0}", sum);
}
}
}
public static float Add(float num1, float num2)
{
return num1 + num2;
}
}
}
I would like for someone to help me by telling me what code I should use in case the input number turns out to be for the second if or third if, if the user doesn't put the right amount (73-77) then id like the user to be able to type in a new value I can use... how do I do that please?
namespace test
{
class Program
{
public static int FahrToCels(int fahr)
{
int cel = (fahr - 32) * 5 / 9;
return cel;
}
static void Main(string[] args)
{
Console.WriteLine("write down temprature: ");
int fahrenheit = int.Parse(Console.ReadLine());
int celsius = FahrToCels(fahrenheit);
Console.Write("Press any key to continue . . .");
Console.ReadKey(true);
do
if (celsius >= 73 && celsius <= 77)
{
Console.WriteLine("now it works ");
}
else if (celsius < 72)
{
Console.WriteLine("");
}
else if (celsius > 77)
{
Console.WriteLine("");
}
while (true);
}
}
}
There are a few major issues with what you have. Attached is working code for what I believe you are looking for, though in your ifs you have Celsius range in the 70s when the point of your Fahrenheit to Celsius converter turns the value into Celsius which would lie in the 20s range.
namespace test
{
class Program
{
public static int FahrToCels(int fahr)
{
int cel = (fahr - 32) * 5 / 9;
return cel;
}
static void Main(string[] args)
{
int celsius;
int fahrenheit;
do
{
Console.WriteLine("Skrive in Temperaturen: ");
fahrenheit = int.Parse(Console.ReadLine());
celsius = FahrToCels(fahrenheit);
Console.Write("Presifs any key to continue . . .");
Console.ReadKey(true);
if (celsius >= 22 && celsius <= 28)
{
Console.WriteLine("now it works ");
//Insert whatever here
break;
}
else if (celsius < 22)
{
//Something to tell them they need to retry
}
else if (celsius > 28)
{
//Something to tell them they need to retry
}
}
while (celsius >= 22 && celsius <= 28);
}
}
}
I would recommend changing the range on your ifs to the values you want the user to input, and also provide the user with some error/retry statement in your elseifs. Also would recommend instead of having two elseifs just use else. Also would remove that stupid readkey() in my opinion.
If you have any questions to my answer leave them in the comments.
If you want to ensure that celsius is in [73..77] range you can try
static void Main(string[] args) {
int fahrenheit;
int celsius;
// Keep asking user until (s)he enters a valid celsius value
while (true) {
Console.WriteLine("Skrive in Temperaturen: ");
// check if value a valid integer, and not say "bla-bla-bla"
if (!int.TryParse(Console.ReadLine(), out fahrenheit)) {
Console.WriteLine("Not an integer value, please, try again");
continue;
}
// fahrenheit is a valid integer value, we can compute corresponding celsius...
celsius = FahrToCels(fahrenheit);
// ... and validate the celsius value then
if (celsius < 73)
Console.WriteLine("Too low temperature (below 73 degree Celsius)");
else if (celsius > 77)
Console.WriteLine("Too high temperature (above 77 degree Celsius)");
else
break; // celsius is valid integer value in [73..77] range
}
// From now on celsius contains integer in [73..77] range
Console.WriteLine("Now it works");
Console.Write("Press any key to continue . . .");
Console.ReadKey(true);
}
I'm not sure how to explain this but I'll try my best since I'm new to c# programming.
I have created a Menu System
string sChoice;
//Menu
Console.WriteLine("1 - Instructions");
Console.WriteLine("2 - New User");
Console.WriteLine("3 - Record & Score");
Console.WriteLine("4 - Exit System");
Console.Write("Please enter your choice between 1-4: ");
sChoice = Console.ReadLine();
Pressing 1 will then take you to the instructions section of the console application and so on.
//Instructions
if (sChoice == "1")
{
Console.WriteLine();
Console.WriteLine("*Instructions*");
Console.WriteLine();
I have tried an else statement which will repeat the menu and prompt the user of an invalid key, however this will only repeat itself another 3 times before closing. Is there a way for me to block any other keys other than 1-4 being entered or a solution to my problem
Because as it seems, if any key other than 1-4 is pressed then the console application will simply close.
This question remembers me when I was young and started programming.
Maybe you want someting like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
while (true)
{
int mainMenuOption = OptionMenu("Instructions", "New User", "Record & Score", "Exit System");
switch (mainMenuOption)
{
case 1: Instructions(); break;
case 2: NewUser(); break;
case 3: RecordAndScore(); break;
case 4: Console.WriteLine("Goodbye.."); return;
}
}
}
static void Instructions()
{
// Handle Instructions here
Console.WriteLine("Instrucctions done");
}
static void NewUser()
{
// Handle New User here
Console.WriteLine("New user done");
}
static void RecordAndScore()
{
// handle recorde and score here
Console.WriteLine("Record & score done");
}
static int OptionMenu(params string[] optionLabels)
{
Console.WriteLine("Please Choose an option");
for (int optionIndex = 0; optionIndex < optionLabels.Length; optionIndex++)
{
Console.Write(optionIndex + 1);
Console.Write(".- ");
Console.WriteLine(optionLabels[optionIndex]);
}
while (true)
{
var input = Console.ReadLine();
int selectedOption;
if (int.TryParse(input, out selectedOption) && selectedOption > 0 && selectedOption <= optionLabels.Length)
{
return selectedOption;
}
else
{
Console.WriteLine("Invalid option, please try again");
}
}
}
}
}
I have a C# Console application that I would like to write using this code but I have tried a couple of things and seem to run a block. I am trying to make a timer on a game at the top but the only way for me to print to the console and sort of keep it is by eliminating the Console.Clear from this Code. Is there a way that I can keep the Countdown timer at the top while Console.Clear is only active for the timer not everything in the console window?
Additionally, does anyone know how to convert the number to format a timeclock like so: 00:05:00?
using System;
using System.Timers;
namespace TimerExample
{
class Program
{
static Timer timer = new Timer(1000);
static int i = 10;
static void Main(string[] args)
{
timer.Elapsed+=timer_Elapsed;
timer.Start();
Console.Read();
}
private static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
i--;
Console.Clear();//here is where I disable and it prints out all the timer in the widow
// if I leave this console window it wipes out my print?
Console.WriteLine("=================================================");
Console.WriteLine(" First Quarter");
Console.WriteLine("");
Console.WriteLine(" Time Remaining: " + i.ToString());
Console.WriteLine("");
Console.WriteLine("=================================================");
if (i == 0)
{
Console.Clear();
Console.WriteLine("");
Console.WriteLine("==============================================");
Console.WriteLine(" Huddle ! ! ! !");
Console.WriteLine("");
Console.WriteLine(" Timeout");
Console.WriteLine("==============================================");
timer.Close();
timer.Dispose();
}
GC.Collect();
}
}
}
Okay here is the extension of the code
I am having issues trying to keep my game on the bottom of the window and really trying to code the countdown timer to be active as soon as the game starts but also keeping my game selection print for the user any suggestions would help
{}....
++++++++++++++++++++++
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
namespace TimerExample
{
class Program
{
static Timer timer = new Timer(1000);
static int i = 300;
private void Run()
{
Header();
Story();
timer.Elapsed += timer_Elapsed;
timer.Start();
// Console.ReadLine();
bool appRunning = true;
bool playerExists = false;
//bool drinkExists = false;
int userInput = 0;
//loop
while (appRunning)
{
Console.WriteLine("\n\n....................\n");
Console.WriteLine("What would you like to do?\n");
Console.WriteLine("1.)Choose Role 2.)Show Credits 3.)Exit Application");
Console.WriteLine(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
Console.WriteLine("Chose a player: ");
//take user input and ocnvert to string to int data type
userInput = Int16.Parse(Console.ReadLine());
//switch statement o flip through menu options
switch (userInput)
{
case 1:
//intelligence to monitor that we only make one sandwich per customer
if (playerExists == false)
{
Console.WriteLine("Does my sandwich exist? Answer is" + playerExists);
Console.WriteLine("Lets make you a snadwich, then shall we??\n");
//set default sandwich variable values
String Quarterback = "Quarterback";
String Runningback = "Runningback";
String Receiver = "Receiver";
//get type of bread from user
Console.Clear();
Console.WriteLine("What type of play would you like?");
Console.WriteLine("Short, Run, Pass Long");
Quarterback = Console.ReadLine();
//get type of Option from user
Console.Clear();
Console.WriteLine("What type of play would you like?");
Console.WriteLine("Left, Right, or Staight");
Runningback = Console.ReadLine();
//get type of jelly from user
Console.Clear();
Console.WriteLine("What type of play would you like?");
Console.WriteLine("Long, Short, or Mid");
Receiver = Console.ReadLine();
//create an instance of the sandwichclass
Player myPlayer = new Player(Quarterback, Runningback, Receiver);
myPlayer.AboutPlayer();
playerExists = true;
}
{
Console.WriteLine("You've already made your role choice!");
}
break;
case 2:
ShowCredits();
break;
case 3:
appRunning = false;
break;
default:
Console.WriteLine("You have not chosen a valid option.");
Console.WriteLine("Please chose from the menu....");
break;
}//end switch
}//end of while
}//end of private void run
private static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
i--;
// Console.Clear();
Console.WriteLine("=================================================");
Console.WriteLine(" First Quarter");
Console.WriteLine("");
Console.WriteLine(" Time Remaining: " + i.ToString());
Console.WriteLine("");
Console.WriteLine("=================================================");
if (i == 0)
{
Console.Clear();
Console.WriteLine("");
Console.WriteLine("==============================================");
Console.WriteLine(" Time Out ! ! ! !");
Console.WriteLine("");
Console.WriteLine(" Huddle");
Console.WriteLine("==============================================");
timer.Close();
timer.Dispose();
}
GC.Collect();
}//end ofprivatestaticvoidtimer
class Player
{
//set default vaulues for our sandwich type
private String Quarterback = "";
private String Runningback = "";
private String Receiver = "";
//build the constructor for the sandwich class
public Player(String Quarterback, String Runningback, String Receiver)
{
this.Quarterback = Quarterback;
this.Runningback = Runningback;
this.Receiver = Receiver;
}
public void AboutPlayer()
{
Console.WriteLine("You have made your selection!");
Console.WriteLine("As");
Console.WriteLine("Press enter to coninue...");
Console.ReadLine();
}
}
static void Main(string[] args)
{
Console.ReadKey();
Program myProgram = new Program();
myProgram.Run();
Console.ReadLine();
}//endofmain
private void ShowCredits()
{
Console.Clear();
Console.WriteLine("An in-class assigment for Intro to Programming");
Console.WriteLine("Cesar Mojarro");
}
private void Header()
{
Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++++++++++++");
Console.WriteLine("+++++++1967 Tackle Football Championships v.1.0 ++++++");
Console.WriteLine("++++++++++++++Studded Diamond Cup ++++++++++++++++++++");
Console.WriteLine("++++++++++++++++++++++By IAM!+++++++++++++++++++++++++");
Console.WriteLine("++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
Console.ReadKey();
}
private void Story()
{
Console.WriteLine("It's the year 1967 and in the First Quarter Steve Miller is running Quarterback for the Packs.");
Console.WriteLine("Young Styler is running Quarterback for the Texan Ranchers.");
Console.WriteLine("Your frontline is hung over from the party last nite, ouch! ");
Console.WriteLine("The team owner is ready to collect on the pay day from the Studded Diamond Cup");
Console.WriteLine("Don't let him replace you for a rookie!");
Console.WriteLine("");
Console.WriteLine("");
Console.ReadKey();
Console.WriteLine("The Coin Toss is about to take place,\nyou are nervous and are about to take a chance at this tackle unit.");
Console.WriteLine("Rules are simple keep the ball running yards,\nstay head strong and keep your eye on defense!");
Console.WriteLine("Don't let them tackle you down and\nreturn you all the way to the goal line by allowing your apponent to score");
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("");
Console.ReadKey();
}
}//endofProgram
}
Use Console.CursorLeft and Console.CursorTop to move the cursor to the line with the time, you can then overwrite that line with your new value.
private void UpdateTime(int i)
{
//Move to the first column.
Console.CursorLeft = 0;
//Move to the 4th row
Console.CursorTop = 3;
//Write your text. Extra spaces to overwrite old numbers
Console.Write(" Time Remaining: " + i.ToString() + " ");
}
You can be even more efficient by figuring out the column i is written to and just overwrite that.
private string _timeRemainingString = " Time Remaining: ";
private void UpdateTime(int i)
{
//Move to the first column that would have had numbers.
Console.CursorLeft = _timeRemainingString.Length;
//Move to the 4th row
Console.CursorTop = 3;
//overwrite just the number portion.
Console.Write(i.ToString() + " ");
}
Additionally, does anyone know how to convert the number to format a timeclock like so: 00:05:00
If i represents the number of seconds left in the game it the easiest solultion would be convert it in to a TimeSpan then you can use time span's formatting to get the format you want.
private void UpdateTime(int i)
{
Console.CursorLeft = _timeRemainingString.Length;
Console.CursorTop = 3;
var time = TimeSpan.FromSeconds(i);
//the `.ToString("c")` on a TimeSpan will give you a time in the format "00:00:00"
//you don't need the extra spaces anymore because the time will always be 8 digits long.
Console.Write(time.ToString("c"));
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConTempConversion_LeeMichelle
{
class Program
{
static void Main(string[] args)
{
double fTemp;
double cTemp;
double convertC;
double convertF;
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
Console.WriteLine("1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit");
Console.WriteLine("3. Exit");
Console.Write("Enter choice: ");
Console.ReadKey();
int ichoice = 0;
do
{
if (ichoice == 1)
{
Console.WriteLine("Enter Fahrenheit temperature: ");
fTemp = int.Parse(Console.ReadLine());
convertC = ConvertCelcius(fTemp);
Console.WriteLine(fTemp + "Fahrenheit is " + convertC + "Celsius");
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
Console.ReadKey();
}
if (ichoice == 2)
{
Console.WriteLine("Enter Celsius temperature: ");
cTemp = int.Parse(Console.ReadLine());
convertF = ConvertFahrenheit(cTemp);
Console.WriteLine(cTemp + "Celsius is " + convertF + "Fahrenheit");
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("____________________________________________________");
Console.ReadKey();
}
if (ichoice == 3)
{
Console.WriteLine("Thank you for using the temperature conversion application. Please come again.");
}
else
{
Console.WriteLine("Invalid choice. Please choose again!");
}
}
while (ichoice > 3);
Console.ReadKey();
}
static double ConvertCelcius(double c){
double f;
return f= 9.0 / 5.0 * c + 32;
}
static double ConvertFahrenheit(double f) {
double c;
return c = 5.0 / 9.0 * (f - 32);
}
}
}
so suppose the user has three options from 1 - 3. After option 3, there will be an error alert. my problem is why this code gives me an infinity loop? what did I do wrong? can I put break after each if statment?
Please help, thank you!
You're creating a do...while loop without anything to ever exit it. When the loop begins, ichoice is already set in stone. So you'll always be stuck in that loop!
You are never assigning a value to ichoice If I were you, I would try something like this:
int ichoice = 0;
int.TryParse(Console.ReadKey().ToString(), out ichoice );
do
{
if (ichoice == 1)
{
Console.WriteLine("Enter Fahrenheit temperature: ");
fTemp = int.Parse(Console.ReadLine());
convertC = ConvertCelcius(fTemp);
Console.WriteLine(fTemp + "Fahrenheit is " + convertC + "Celsius");
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
int.TryParse(Console.ReadKey().ToString(), out ichoice );
Add the int.TryParse(Console.ReadKey().ToString(), out ichoice ); everywhere you have Console.Readline(). What this is doing is getting the user input and converting it to an integer (if it's not an integer, then the value is 0).
Also add this:
if (ichoice == 3)
{
Console.WriteLine("Thank you for using the temperature conversion application. Please come again.");
break;
}
else
{
Console.WriteLine("Invalid choice. Please choose again!");
int.TryParse(Console.ReadKey().ToString(), out ichoice );
}
Finally, remove this (I'm not quite sure what it was for...)
while (ichoice > 3);
Console.ReadKey();
When you need to do some prep work before your condition, the most straightforward way involves combining your loop with a separate structure.
This is the format to use when your loop condition is at the beginning of the loop:
prep work
while (condition) // if false then loop body will never run
{
loop body
}
This is the format to use when the loop condition is at the end of the loop:
prep work
do
{
loop body
}
while (condition); // loop body will always execute at least once
In this case, you have some prep work to do before each iteration--you want to get the key press from the user each time. For this, I recommend the following from Code Complete:
while (true) // loop termination condition is inside the loop
{
prep work
if (condition)
{
break;
}
loop body
}
In your case, it would look something like:
Console.Write("Enter choice: ");
while (true) // loop termination condition is inside the loop
{
Console.ReadKey();
if (ichoice == 3)
{
Console.WriteLine(...);
break;
}
...
}
Also, consider changing most of your ifs into else ifs; otherwise, you're repeatedly checking the condition even when you've gone through one case.
you should assign a value to iChoice. and set your while to read a terminating character. like:
namespace YourNameSpace
{
static void Main(string[] args)
{
double fTemp;
double cTemp;
double convertC;
double convertF;
int iChoice;
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
Console.WriteLine("1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit");
Console.Write("Enter choice(0 to exit): ");
iChoice = Console.Read();
do{
switch(iChoice)
{
case 1:
Console.WriteLine("Enter Fahrenheit temperature: ");
fTemp = int.Parse(Console.ReadLine());
convertC = ConvertCelcius(fTemp);
Console.WriteLine(fTemp + "Fahrenheit is " + convertC + "Celsius");
case 2:
Console.WriteLine("Enter Celsius temperature: ");
cTemp = int.Parse(Console.ReadLine());
convertF = ConvertFahrenheit(cTemp);
Console.WriteLine(cTemp + "Celsius is " + convertF + "Fahrenheit");
}
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
Console.WriteLine("1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit");
Console.Write("Enter choice(0 to exit): ");
iChoice = Console.Read();
}while(iChoice != 0);
}
static double ConvertCelcius(double c){
double f;
return f= 9.0 / 5.0 * c + 32;
}
static double ConvertFahrenheit(double f) {
double c;
return c = 5.0 / 9.0 * (f - 32);
}
}
Each time you call Console.ReadKey you should store returning value.You are receiving input from user but you didn't store it anywhere.
First you can create a function to get ichoice, and force user to enter the correct value:
static void GetChoice(ref int ichoice)
{
string input = Console.ReadLine();
Console.Write("Enter choice: ");
bool result = int.TryParse(input, out ichoice);
if (!result)
{
while (!result && ichoice > 3)
{
Console.WriteLine("Invalid value.Try again:");
input = Console.ReadLine();
result = int.TryParse(input, out ichoice);
}
}
}
Then use this function whenever you need to make a choice.
Here is the working version or your program:
double fTemp;
double cTemp;
double convertC;
double convertF;
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
Console.WriteLine("1. Fahrenheit to Celsius");
Console.WriteLine("2. Celsius to Fahrenheit");
Console.WriteLine("3. Exit");
int ichoice = 0;
GetChoice(ref ichoice);
do
{
if (ichoice == 1)
{
Console.WriteLine("Enter Fahrenheit temperature: ");
fTemp = int.Parse(Console.ReadLine());
convertC = ConvertCelcius(fTemp);
Console.WriteLine(fTemp + "Fahrenheit is " + convertC + "Celsius");
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("_________________________________________________");
GetChoice(ref ichoice);
}
if (ichoice == 2)
{
Console.WriteLine("Enter Celsius temperature: ");
cTemp = int.Parse(Console.ReadLine());
Console.WriteLine(cTemp + "Celsius is " + cTemp + "Fahrenheit");
Console.WriteLine("Welcome to the temperature conversion application");
Console.WriteLine("____________________________________________________");
GetChoice(ref ichoice);
}
if (ichoice == 3)
{
Console.WriteLine("Thank you for using the temperature conversion application. Please come again.");
}
else
{
Console.WriteLine("Invalid choice. Please choose again!");
}
}
while (ichoice < 3);
}
static double ConvertCelcius(double c)
{
double f;
return f = 9.0 / 5.0 * c + 32;
}
static double ConvertFahrenheit(double f)
{
double c;
return c = 5.0 / 9.0 * (f - 32);
}
And here is the full code: http://pastebin.com/bkegSAFL