C# console.write showing statement - c#

This is part of my code and I'm trying to make console.write to show new statement of "Please re-enter number greater than 20 : " only.
The problem is when I run my code it show "Please re-enter number greater than 20 : " as well as previous statement ("Enter amount of fuel used in litres : "). in one line.
How can I make it not to show first write statement ??
static double InputFuel()
{
double fFuel;
string text;
bool badValue = true;
do
{
Console.Write("Enter amount of fuel used in litres : ");
text = Console.ReadLine();
if (double.TryParse(text, out fFuel) && fFuel >= 20)
{
badValue = false;
}
else
{
Console.WriteLine("\n\t {0} is below the minimum value of 20 \n\n", text);
Console.Write("Please re-enter number greater than 20 : ");
}
} while (badValue);
return fFuel;
}//end InputTemp

Move the line Console.Write("Enter amount of fuel used in litres : "); outside the while-loop. In your example it is inside the while loop, so it is repeated every time an incorrect answer is entered. If you move it in front of the loop, it will only be written once to the console.
...
bool badValue = true;
Console.Write("Enter amount of fuel used in litres : ");
do
{
text = Console.ReadLine();
...

You can use Console.Clear() to clear the current contents of the Console. https://msdn.microsoft.com/en-us/library/system.console.clear(v=vs.110).aspx
For instance
static double InputFuel()
{
double fFuel;
string text;
bool badValue = true;
do
{
Console.Write("Enter amount of fuel used in litres : ");
text = Console.ReadLine();
if (double.TryParse(text, out fFuel) && fFuel >= 20)
{
badValue = false;
}
else
{
Console.Clear();
Console.WriteLine("\n\t {0} is below the minimum value of 20 \n\n", text);
Console.Write("Please re-enter number greater than 20 : ");
}
} while (badValue);
return fFuel;
}

static double InputFuel()
{
double fFuel;
string text;
bool badValue = true;
bool notFirst = false;
do
{
if(!notFirst)
Console.Write("Enter amount of fuel used in litres : ");
notFirst = true;
text = Console.ReadLine();
if (double.TryParse(text, out fFuel) && fFuel >= 20)
{
badValue = false;
}
else
{
Console.WriteLine("\n\t {0} is below the minimum value of 20 \n\n", text);
Console.Write("Please re-enter number greater than 20 : ");
}
} while (badValue);
return fFuel;
}

If I understood correctly, your problem is only an algorithmic problem :
static double InputFuel()
{
double fFuel;
string text;
bool badValue = true;
Console.Write("Enter amount of fuel used in litres : ");
do
{
text = Console.ReadLine();
if (double.TryParse(text, out fFuel) && fFuel >= 20)
{
badValue = false;
}
else
{
Console.Clear();
Console.WriteLine("\n\t {0} is below the minimum value of 20 \n\n", text);
Console.Write("Please re-enter number greater than 20 : ");
}
} while (badValue);
return fFuel;
}//end InputTemp
By putting out the first write out of the loop, it only shows the first time and then does not come again. If you want it to completely disappear, just add a Console.Clear(); in the else statement to erase what was displayed before, and it's done.

I suggest changing the loop into infinite one; if question should be stated just once pull it out of the loop:
Console.Write("Enter amount of fuel used in litres : ");
while (true) {
text = Console.ReadLine();
if (!double.TryParse(text, out fFuel))
Console.Write("Please re-enter number in correct format: ");
else if (fFuel <= 0)
Console.Write("Please re-enter number greater than 0 : ");
else if (fFuel >= 20)
Console.Write("Please re-enter number less than 20 : ");
else
break;
}

Related

Keeping numbers in a range

I am attempting to get some data validation done but I am really struggling with that. I have been using If statements and was hoping If (pun intended) someone could help me. I am very new to the whole thing and have a massive piece that needs to be done so far I have managed but this got me stumped. I really would like a push or something in the correct direction because it feels like I am rubbing my head against a piece of sandpaper
int iNumber1;
int iNumber2;
Console.WriteLine("Please give me 2 number between -10 and +10 and ill add them together");
Console.Write("Please enter a number: ");
iNumber1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter a number: ");
iNumber2 = Convert.ToInt32(Console.ReadLine());
int iResult;
//here i get the adding bit done
iResult = iNumber1 + iNumber2;
//bool bUserInput = false;
//while (!bUserInput)
//{
// string sInput = Console.ReadLine();
// if (iNumber1 < -10)
// {
// Console.WriteLine("Your are out of range please stay between -10 and +10");
// }
// if (iNumber1 < 10)
// {
// Console.WriteLine("Your are out of range please stay between -10 and +10 ");
// }
// if (iNumber2 < -10)
// {
// Console.WriteLine("Your are out of range please stay between -10 and +10");
// }
// if (iNumber2 < 10)
// {
// Console.WriteLine("Your are out of range please stay between -10 and +10");
// }
//}
if (iResult <= -10 || iResult >= 11)
{
Console.WriteLine("Out of range calculation is ignored");
}
else
{
Console.WriteLine("That number is vaild and its {0}", iResult);
}
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Please give me 2 number between -10 and +10 and ill add them together\n");
int iNumber1 = readNumber();
int iNumber2 = readNumber();
int iResult = iNumber1 + iNumber2;
Console.WriteLine("The sum of {0} + {1} is {2}", iNumber1, iNumber2, iResult);
}
//you should use functions to avoid code repetition.
//the function below reads the user input and tries to convert it into a number.
//the validation rule is applied inside the loop.
private static int readNumber()
{
bool bUserInput;
int number;
//below is a loop that runs at least once. the loop continues
//iterating while the condition evaluates to true, otherwise it ends
//and control goes to the statement immediately after it.
do
{
Console.WriteLine("Please enter a number: ");
//Int32.TryParse receives as arguments a string to parse and
//an integer as an output argument (you need the out keyword)
//it returns true if it the string could be successfully converted
//into an integer and false if it couldn't.
bUserInput = Int32.TryParse(Console.ReadLine(), out number);
if (!bUserInput)//this will be true if the user input could not be converted
{
Console.WriteLine("Input could not be converted into an integer number");
//the continue statement is used inside a loop to skip the rest of it
//and jump directly to the test condition
continue;
}
if (number < -10 || number > 10)//the validation
{
//the error message
Console.WriteLine("Your are out of range please stay between -10 and +10");
//make sure we set the flag to false because in this case,
//Int32.TryParse has set it to true, but input is still invalid
//by the validation rules.
bUserInput = false;
}
else//the number is in range, set the flag to true
{
Console.WriteLine("Good Job!\n");
//set the flag to true, so the loop can end.
bUserInput = true;
}
}while(!bUserInput);//while this evaluates to true, the loop continues.
return number;
}
}
So you need a way to validate that a number is between -10 and +10 (inclusive). That should be easy:
bool isValid(int i)
{
return (i >= -10) && (i <= 10);
}
now you need a function to see if two numbers are both valid:
bool areValid(int i1, int i2)
{
return isValid(i1) && isValid(i2);
}
Now just assume that input is not valid, and loop until it is:
bool isValid = false;
while(!isValid)
{
Console.WriteLine("Please give me 2 number between -10 and +10 and I'll add them together");
Console.Write("Please enter a number: ");
iNumber1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter a number: ");
iNumber2 = Convert.ToInt32(Console.ReadLine());
isValid = areValid(iNumber1, iNumber2);
if(!isValid)
{
Console.WriteLine("Out of range calculation is ignored");
}
}
Now you know you have two valid numbers and can continue with the rest of your program.

How to put Pin in 4 digits only when entering a PIN and how to verified it?

I don't know the codes as I'm a beginner in c#, so could anyone help me with these? I want my pin to enter in 4 digits only and re verified the pin to continue in the menu?
{
class program
{
public static void Main()
{
int amount = 1000, deposit, withdraw;
int choice, pin = 0, x = 0;
Console.WriteLine("Enter Your Pin Number ");
pin = int.Parse(Console.ReadLine());
while (true)
{
Console.WriteLine("********Welcome to ATM Service**************\n");
Console.WriteLine("1. Check Balance\n");
Console.WriteLine("2. Withdraw Cash\n");
Console.WriteLine("3. Deposit Cash\n");
Console.WriteLine("4. Quit\n");
Console.WriteLine("*********************************************\n\n");
Console.WriteLine("Enter your choice: ");
choice = int.Parse(Console.ReadLine());
switch (choice)
{
case 1:
Console.WriteLine("\n YOUR BALANCE IN Rs : {0} ", amount);
break;
case 2:
Console.WriteLine("\n ENTER THE AMOUNT TO WITHDRAW: ");
withdraw = int.Parse(Console.ReadLine());
if (withdraw % 100 != 0)
{
Console.WriteLine("\n PLEASE ENTER THE AMOUNT IN MULTIPLES OF 100");
}
else if (withdraw > (amount - 500))
{
Console.WriteLine("\n INSUFFICENT BALANCE");
}
else
{
amount = amount - withdraw;
Console.WriteLine("\n\n PLEASE COLLECT CASH");
Console.WriteLine("\n YOUR CURRENT BALANCE IS {0}", amount);
}
break;
case 3:
Console.WriteLine("\n ENTER THE AMOUNT TO DEPOSIT");
deposit = int.Parse(Console.ReadLine());
amount = amount + deposit;
Console.WriteLine("YOUR BALANCE IS {0}", amount);
break;
case 4:
Console.WriteLine("\n THANK U USING ATM");
break;
}
}
Console.WriteLine("\n\n THANKS FOR USING OUT ATM SERVICE");
}
}
}
I suggest something like this:
// read size (4) digits
private static string ReadPin(int size = 4) {
StringBuilder sb = new StringBuilder(size);
while (sb.Length < size) {
var key = Console.ReadKey(true); // we don't want to show the secret pin on the screen
// Uncomment, if you want to let user escape entering the PIN
// if (key.Key == ConsoleKey.Escape) {
// return "";
// }
if (key.KeyChar >= '0' && key.KeyChar <= '9') {
sb.Append(key.KeyChar);
Console.Write('*'); // let's show * instead of actual digit
}
}
return sb.ToString();
}
...
// private: there's no need for Main to be public
private static void Main() {
...
Console.WriteLine("Enter Your Pin Number ");
int pin = int.Parse(ReadPin());
If you want to verify the given string (pin) which is expected to be of length size, you can try either Linq
using System.Linq;
...
string pin = ...
int size = 4;
bool isValidPin = pin.Length == size && pin.All(c => c >= '0' && c <= '9');
Or regular expressions:
using System.Text.RegularExpressions;
...
bool isValidPin = Regex.IsMatch(pin, $"^[0-9]{{{size}}}$");
int password;
int repassword
Do{
Console.WriteLine("\n Enter the password");
password= int.Parse(Console.ReadLine()); //first password
string ps = Convert.ToString(password);
}while(ps.Length!=4) //request the password if is not composed by 4 digits
//menu part//
Do{
Console.WriteLine("\n Reinsert the password");
repassword= int.Parse(Console.ReadLine()); //reinsert password
} while(repassword!=password)

Extra brackets expected? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
The Following :
if (parseok == false)
{
Console.WriteLine("Error : Please enter valid numeric Value ");
Console.ReadLine();
Environment.Exit(0);
}
//Is currently working fine, however, I am wanting to change the if statement to a while loop - for error checking purposes. When I change the code to this :
while (parseok == false)
{
Console.WriteLine("Error : Please enter valid numeric Value ");
Console.ReadLine();
Console.Write("Please enter minutes for your first run: ");
parseok = int.TryParse(Console.ReadLine(), out run1m);
}
//I am recieveing an error message saying that I'm missing a close bracket, when I add the close bracket the whole program becomes riddled with errors. What am I forgetting to do?
//I will add the entire project's code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
//Ajdin Karahodzic
//ID : KARAD1301
static void Main(string[] args)
{
String membertype = "";
//Declaration of Variables
string name = "";
string member = "";
string gender = "";
int run1m = 0;
int run1s = 0;
int run2m = 0;
int run2s = 0;
int run3m = 0;
int run3s = 0;
int run1total = 0;
int run2total = 0;
int run3total = 0;
int totalsecs = 0;
int avgsecs = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
bool parseok = false;
string menu = "";
int run1tempS = 0;
int run1tempM = 0;
int run1tempH = 0;
int run2tempS = 0;
int run2tempM = 0;
int run2tempH = 0;
int run3tempS = 0;
int run3tempM = 0;
int run3tempH = 0;
while (menu != "x")
{
Console.WriteLine("Please choose from the following : ");
Console.WriteLine("Enter Runner Details (R) : ");
Console.WriteLine("Enter run times (T) : ");
Console.WriteLine("Display runner results (D) : ");
Console.WriteLine("Exit the program (X) ");
menu = Console.ReadLine();
switch (menu)
{
//CLOSE PROGRAM SWITCH
case "x":
case "X":
Environment.Exit(0);
break;
//ENTER RUNNER DATA SWITCH
case "r":
case "R":
Console.Write("Please enter your name: ");
name = Console.ReadLine();
while (string.IsNullOrEmpty(name))
{
Console.WriteLine("Error : Please ensure you have entered your name, press enter to continue ");
Console.ReadLine();
Console.Write("Please enter your name: ");
name = Console.ReadLine();
}
Console.Write("Please enter your membership number: ");
member = Console.ReadLine();
while (member.Length != 5)
{
Console.WriteLine("Error : Membership number must be 5 characters long, press enter to continue ");
Console.ReadLine();
Console.Write("Please enter your membership number: ");
member = Console.ReadLine();
}
char first = member[0];
while (first != 'o' && first != 'O' && first != 's' && first != 'S' && first != 'j' && first != 'J' && first != 'C' && first != 'c')
{
Console.WriteLine("Error : Membership number must begin with O, S, J or C, press enter to continue ");
Console.ReadLine();
Console.Write("Please enter your membership number: ");
member = Console.ReadLine();
}
if (first == 'o' || first == 'O')
{
membertype = "Ordinary Member";
}
else if (first == 's' || first == 'S')
{
membertype = "Student Member";
}
else if (first == 'j' || first == 'J')
{
membertype = "Junior Member";
}
else if (first == 'c' || first == 'C')
{
membertype = "Child Member";
}
string response = "";
Console.Write("Please enter your gender (m) or (f) : ");
response = Console.ReadLine();
gender = response;
while (gender != "m" && gender != "M" && gender != "f" && gender != "F")
{
Console.WriteLine("Error : Gender must be either : M / m (For Male) or F / f (For Female), press enter to continues ");
Console.ReadLine();
Console.Write("Please enter your gender (m) or (f) : ");
response = Console.ReadLine();
gender = response;
}
break;
//ENTER RUN TIMES - SWITCH
case "T":
case "t":
//Prompt for user input; collect and store data.
/*---------RUN 1 INPUT---------
-----------------------------*/
//MINUTES
Console.Write("Please enter minutes for your first run: ");
parseok = int.TryParse(Console.ReadLine(), out run1m);
while (parseok == false)
{
Console.WriteLine("Error : Please enter valid numeric Value ");
Console.ReadLine();
Console.Write("Please enter minutes for your first run: ");
parseok = int.TryParse(Console.ReadLine(), out run1m);
}
else if (run1m < 15 || run1m > 180)
{
Console.WriteLine("Error : Minutes cannot be less than 15 or greater than 180");
Console.ReadLine();
Environment.Exit(0);
}
//SECONDS
Console.Write("Please enter seconds for your first run: ");
parseok = int.TryParse(Console.ReadLine(), out run1s);
if (parseok == false)
{
Console.WriteLine("Error : Please enter valid numeric Value ");
Console.ReadLine();
Environment.Exit(0);
}
else if (run1s < 0 || run1s > 59)
{
Console.WriteLine("Error : Seconds must be between 0 and 59 ");
Console.ReadLine();
Environment.Exit(0);
}
Console.WriteLine();
/*---------RUN 2 INPUT---------
------------------------------*/
Console.Write("Please enter minutes for your second run: ");
parseok = int.TryParse(Console.ReadLine(), out run2m);
if (parseok == false)
{
Console.WriteLine("Error : Please enter valid numeric Value ");
Console.ReadLine();
Environment.Exit(0);
}
else if (run2m < 15 || run2m > 180)
{
Console.WriteLine("Error : Minutes cannot be less than 15 or greater than 180");
Console.ReadLine();
Environment.Exit(0);
}
Console.Write("Please enter seconds for your second run: ");
run2s = int.Parse(Console.ReadLine());
if (parseok == false)
{
Console.WriteLine("Error : Please enter valid numeric Value ");
Console.ReadLine();
Environment.Exit(0);
}
else if (run2s < 0 || run2s > 59)
{
Console.WriteLine("Error : Seconds must be between 0 and 59 ");
Console.ReadLine();
Environment.Exit(0);
}
Console.WriteLine();
/*---------RUN 3 INPUT---------
------------------------------*/
Console.Write("Please enter minutes for your third run: ");
parseok = int.TryParse(Console.ReadLine(), out run3m);
if (parseok == false)
{
Console.WriteLine("Error : Please enter valid numeric Value ");
Console.ReadLine();
Environment.Exit(0);
}
else if (run3m < 15 || run3m > 180)
{
Console.WriteLine("Error : Minutes cannot be less than 15 or greater than 180");
Console.ReadLine();
Environment.Exit(0);
}
Console.Write("Please enter seconds for your third run: ");
run3s = int.Parse(Console.ReadLine());
if (parseok == false)
{
Console.WriteLine("Error : Please enter valid numeric Value ");
Console.ReadLine();
Environment.Exit(0);
}
else if (run3s < 0 || run3s > 59)
{
Console.WriteLine("Error : Seconds must be between 0 and 59 ");
Console.ReadLine();
Environment.Exit(0);
}
Console.WriteLine();
break;
case "d":
case "D":
// CALCULATIONS
//Converting individual run times to seconds
run1total = (run1m * 60) + run1s;
run2total = (run2m * 60) + run2s;
run3total = (run3m * 60) + run3s;
//Convert individual times to hours, mins, secs.
// RUN1
run1tempS = (run1total % 60);
run1tempM = ((run1total / 60) % 60);
run1tempH = ((run1total / 3600) % 60);
// RUN2
run2tempS = (run2total % 60);
run2tempM = ((run2total / 60) % 60);
run2tempH = ((run2total / 3600) % 60);
// RUN3
run3tempS = (run3total % 60);
run3tempM = ((run3total / 60) % 60);
run3tempH = ((run3total / 3600) % 60);
//Calculate average time
totalsecs = (run1total + run2total + run3total);
avgsecs = (totalsecs / 3);
seconds = (avgsecs % 60);
minutes = ((avgsecs / 60) % 60);
hours = ((avgsecs / 3600) % 60);
//Display results
Console.WriteLine();
Console.WriteLine("==========================================================================");
Console.WriteLine("10 Km results for: ");
Console.WriteLine("{0} [{1}] - {2}, {3} ", name, member, membertype, gender.ToUpper());
Console.WriteLine("Run 1 - {0} hr(s) {1} min(s) {2} sec(s). ", run1tempH, run1tempM, run1tempS);
Console.WriteLine("Run 2 - {0} hr(s) {1} min(s) {2} sec(s). ", run2tempH, run2tempM, run2tempS);
Console.WriteLine("Run 3 - {0} hr(s) {1} min(s) {2} sec(s). ", run3tempH, run3tempM, run3tempS);
Console.WriteLine();
Console.WriteLine("Average 10km run time is : {0} hours {1} minutes {2} seconds. ", hours, minutes, seconds);
break;
default:
Console.WriteLine("Incorrect input, please try again ");
break;
}
Console.ReadLine();
}
}
}
}
On line 161 you are doing an else if but there fore you did'nt specify any if.
I don't know what your doing in your code. But either remove the else in the else if statement or create an if statement before the else if.
An else if statement comes after an if statement or else if statement and can not be the first one in a comparison.
Solution example
So by adding an if before else if will solve the problem. (Notice I don't now what your program needs to do so you need to check what condition check you have to do.)
Your problem is the left over
else
on line 163. Removing that allows the code to compile, but I'm not going to verify the behaviour.

Breaking out of a loop when user inputs quit or exit c#

I'm having trouble with looping my program so that it breaks out of the loop if user enters "quit" or "exit".
When I type any string, my program crashes as it tries to parse the string input to an int. Any advice?
namespace DiceRolling
{
/* We’re going to write a program that makes life easier for the player of a game like this. Start the
program off by asking the player to type in a number of dice to roll.Create a new Random
object and roll that number of dice.Add the total up and print the result to the user. (You should
only need one Random object for this.) For bonus points, put the whole program in a loop and allow them to keep typing in numbers
until they type “quit” or “exit”. */
class DiceRolling
{
static void RollDice(int numTries)
{
Random random = new Random();
//Console.Write("Please enter the number of dice you want to roll: ");
//int numTries = Convert.ToInt32(Console.ReadLine());
int sum = 0;
int dieRoll;
for (int i = 1; i <= numTries; i++)
{
dieRoll = random.Next(6) + 1;
Console.WriteLine(dieRoll);
sum += dieRoll;
}
Console.WriteLine("The sum of your rolls equals: " + sum);
}
static void Main(string[] args)
{
while (true)
{
Console.Write("Please enter the number of dice you want to roll: ");
string input = Console.ReadLine();
int numTries = Convert.ToInt32(input);
//bool isValid = int.TryParse(input, out numTries);
RollDice(numTries);
Console.ReadKey();
if (input == "quit" || input == "exit")
break;
}
}
}
}
Tigrams is pretty close, this is slightly better
Console.Write("Please enter the number of dices you want to roll: ");
string input = Console.ReadLine();
while (input != "quit" && input != "exit")
{
int numTries = 0;
if (int.tryParse(input, out numTries)
{
RollDice(numTries);
}
Console.Write("Please enter the number of dices you want to roll: ");
input = Console.ReadLine();
}
tried to make it as similar as possible to what you have
while (true)
{
Console.Write("Please enter the number of dices you want to roll: ");
string input = Console.ReadLine();
int numTries;
if (int.TryParse(input, out numTries))
{
RollDice(numTries);
}
else if(input == "quit" || input == "exit")
{
break;
}
}
while (true)
{
Console.Write("Please enter the number of dices you want to roll: ");
string input = Console.ReadLine();
if (input == "quit" || input == "exit") //check it immediately here
break;
int numTries = 0;
if(!int.TryParse(input, out numTries)) //handle not valid number
{
Console.WriteLine("Not a valid number");
continue;
}
RollDice(numTries);
Console.ReadKey();
}
Try int numTries =int.Parse(input != null ? input: "0");

How to reloop the game and ask something

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

Categories