I am trying to make a simple program where the user tries to guess numbers between 1 and 25 until they guess the right one. I am trying to make the input received as an integer so that I can use greater than and less than signs. When I use the command I found on another answer in this forum, it says that there is an error. What am I doing wrong?
int score = 0;
int add = 1;
while (add == 1)
{
Console.WriteLine("Guess A Number Between 1 and 25");
string input = int.Parse(Console.ReadLine());
score += add;
if (input == 18)
{
Console.WriteLine("You Did It!");
Console.WriteLine("Your Score was " + score);
break;
}
else if (input > 25)
{
Console.WriteLine("Error.");
}
else
{
Console.WriteLine("Try Again. Score: " + score);
}
}
Store their response from ReadLine() as a String, then use int.TryParse() to attempt to convert that String to an Integer. The code below is written to show you all the possible states that could occur using if else blocks. I've also used a bool to indicate when the game should end instead of using a break statement:
static void Main(string[] args)
{
int number;
string input;
bool guessed = false;
int score = 0;
while (!guessed)
{
Console.Write("Guess A Number Between 1 and 25: ");
input = Console.ReadLine();
if (int.TryParse(input, out number))
{
if(number>=1 && number<=25)
{
score++;
if (number == 18)
{
guessed = true;
Console.WriteLine("You Did It!");
Console.WriteLine("Your Score was " + score);
}
else
{
Console.WriteLine("Try Again. Score: " + score);
}
}
else
{
Console.WriteLine("Number must be between 1 and 25!");
}
}
else
{
Console.WriteLine("That's not a number!");
}
Console.WriteLine();
}
Console.Write("Press Enter to Quit.");
Console.ReadLine();
}
Related
I'm new to C# and want to implement loops , right now I'm using goto statement and labels but I have read that it is not suggested to use goto statement
so i was thinking to implement loops instead of goto and labels , byt i dont know how can i replace goto with loops
and if possible please also give a small explanation of the answer
here is my code with goto and labels
using System;
/* A simple coffee ordering program
* used switch,if else and lable*/
class Program
{
public static void Main()
{
int TotalCoffeeCost = 0;
// Start is a lable to point to this location so i can use it in goto
Start:
Console.WriteLine("");
Console.WriteLine(" Please enter your coffee size : 1 - small, 2 - medium, 3 - large");
Console.Write(" ");
int CoffeeChoice = int.Parse(Console.ReadLine());
switch (CoffeeChoice)
{
case 1:
TotalCoffeeCost += 2;
break;
case 2:
TotalCoffeeCost += 5;
break;
case 3:
TotalCoffeeCost += 7;
break;
default:
Console.WriteLine("");
Console.WriteLine(" Please enter a vaild choice");
goto Start;
}
// YesOrNo is a lable to point to this location so i can use it in goto
YesOrNo:
Console.WriteLine("");
Console.WriteLine(" Do you want have another coffee : Y or N (Yes or No) ?");
Console.Write(" ");
string UserChoice = Console.ReadLine();
string upperCaseChoice = UserChoice.ToUpper();
if (upperCaseChoice == "Y" || upperCaseChoice == "YES")
{
goto Start;
}else if (upperCaseChoice == "N" || upperCaseChoice == "NO")
{
goto LastConfirmation;
}
else
{
Console.WriteLine("");
Console.WriteLine(" Please enter a vailed choice");
goto YesOrNo;
}
// LastConfirmation is a lable to point to this location so i can use it in goto
LastConfirmation:
Console.WriteLine(" ");
Console.WriteLine(" Can i bring you the bill: y or n (yes or no)");
Console.Write(" ");
string Anything = Console.ReadLine();
string UpperCaseAnything = Anything.ToUpper();
if(UpperCaseAnything == "Y" || UpperCaseAnything == "YES")
{
goto Amount;
}
else if (UpperCaseAnything == "N" || UpperCaseAnything == "NO")
{
goto Start;
}
else
{
Console.WriteLine("");
Console.WriteLine(" Please enter a vaild choice");
goto LastConfirmation;
}
// Amount is a lable to point to this location so i can use it in goto
Amount:
Console.WriteLine("");
Console.WriteLine(" Your total bill amount is = {0}$", TotalCoffeeCost);
Console.WriteLine("");
Console.WriteLine(" Please pay the amount by entering the amount bellow");
Console.Write(" ");
int EnterdAmt = int.Parse(Console.ReadLine());
if(EnterdAmt != TotalCoffeeCost)
{
Console.WriteLine("");
Console.WriteLine(" Please pay the correct amount");
goto Amount;
}
else
{
Console.WriteLine("");
Console.WriteLine(" Thank for buying coffee, Hope you got a amazing experience");
}
}
}
Just use while loops and methods to make this work.
Your Start method could look like this:
public void Start(int TotalCoffeCost)
{
Console.WriteLine("");
Console.WriteLine(" Please enter your coffee size : 1 - small, 2 - medium, - large");
Console.Write(" ");
int CoffeChoice = 0;
do
{
CoffeChoice = int.Parse(Console.ReadLine());//Asking for Choice until you put in 1,2 or 3
}while(CoffeChoice != 1 | CoffeChoice != 2 | CoffeChoice != 3)
switch (CoffeeChoice)
{
case 1:
TotalCoffeeCost += 2;
break;
case 2:
TotalCoffeeCost += 5;
break;
case 3:
TotalCoffeeCost += 7;
break;
}
}
And you can call the method like this:
public static void Main()
{
int TotalCoffeeCost = 0;
Start(TotalCoffeCost);
}
We can use methods and a simple bool "lock" that either keeps you inside the while loop, or breaks out of it when conditions are met:
using System;
/* A simple coffee ordering program
* used switch,if else and lable*/
class Program
{
public static void Main()
{
var exiting = false;
while (!exiting)
{
programLoop();
}
}
private int askForCoffee()
{
int totalCoffeeCost = 0;
bool invalidChoice = true;
while(invalidChoice)
{
Console.WriteLine("");
Console.WriteLine(" Please enter your coffee size : 1 - small, 2 - medium, 3 - large");
Console.Write(" ");
int CoffeeChoice = int.Parse(Console.ReadLine());
switch (CoffeeChoice)
{
case 1:
totalCoffeeCost += 2;
invalidChoice = false;
break;
case 2:
totalCoffeeCost += 5;
invalidChoice = false;
break;
case 3:
totalCoffeeCost += 7;
invalidChoice = false;
break;
default:
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
}
}
return totalCoffeeCost;
}
private void programLoop()
{
int TotalCoffeeCost = 0;
TotalCoffeeCost += askForCoffee();
var invalidChoice = true;
while(invalidChoice)
{
Console.WriteLine("");
Console.WriteLine(" Do you want have another coffee : Y or N (Yes or No) ?");
Console.Write(" ");
string UserChoice = Console.ReadLine();
string upperCaseChoice = UserChoice.ToUpper();
if (upperCaseChoice == "Y" || upperCaseChoice == "YES")
{
TotalCoffeeCost += askForCoffee(); //Note here that we did not set invalidChoice to false, meaning it will loop again
}
else if (upperCaseChoice == "N" || upperCaseChoice == "NO")
{
invalidChoice = false;
}
else
{
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
}
}
invalidChoice = true;
while(invalidChoice)
{
Console.WriteLine(" ");
Console.WriteLine(" Can i bring you the bill: y or n (yes or no)");
Console.Write(" ");
string Anything = Console.ReadLine();
string UpperCaseAnything = Anything.ToUpper();
if(UpperCaseAnything == "Y" || UpperCaseAnything == "YES")
{
invalidChoice = false;
}
else if (UpperCaseAnything == "N" || UpperCaseAnything == "NO")
{
return;
}
else
{
Console.WriteLine("");
Console.WriteLine(" Please enter a valid choice");
}
}
invalidChoice = true;
while(invalidChoice)
{
Console.WriteLine("");
Console.WriteLine(" Your total bill amount is = {0}$", TotalCoffeeCost);
Console.WriteLine("");
Console.WriteLine(" Please pay the amount by entering the amount bellow");
Console.Write(" ");
int EnterdAmt = int.Parse(Console.ReadLine());
if(EnterdAmt != TotalCoffeeCost)
{
Console.WriteLine("");
Console.WriteLine(" Please pay the correct amount");
}
else
{
invalidChoice = false;
}
}
Console.WriteLine("");
Console.WriteLine(" Thank for buying coffee, Hope you got a amazing experience");
}
}
{
bool stayInLoop = true;
while(stayInLoop)
{
Console.WriteLine("Enter Yor Number");
var PlusA = Console.ReadLine();
Console.WriteLine("Enter Yor Number");
var PlusB = Console.ReadLine();
if(PlusA == ';')
{
stayInLoop = false;
break;
}
else if(PlusB == ';')
{
stayInLoop = false;
break;
}
else
{
Console.WriteLine("Answer =");
Console.WriteLine(PlusA + PlusB);
}
}
}
I want to make a plus calculator, I want to let the user type more then 2 numbers, keep asking for PlusC, PlusD, until they type the symbol ; .
For example the user numbers in PlusA PlusB PlusC and in PlusD, he/she type ; so it should print PlusA + PlusB + PlusC
If he type a number in PlusD, it should ask for PlusE, until he/she type ;, it should sum up all the number before
And I want to auto the process, The program will ask for PlusA to PlusZ itself instead of int it my own, how to do that? (I know I am not saying it clearly, coz i can't find better words)
You want to add numbers until the user enters ;. You should use loops for that. Here's the complete solution that uses a for loop:
switch(exp)
{
case "+":
{
var sum = 0;
for(;;)
{
Console.WriteLine("Enter Yor Number");
var line = Console.ReadLine();
if (line == ";") break;
sum += Convert.ToInt32(line);
}
Console.WriteLine(sum);
break;
}
}
Here we repeat the part inside the loop over and over, accumulating entered numbers into sum variable until the user enters ; - that's when we end the loop with break.
Use a while loop:
switch(exp)
{
case "+":
int sum = 0;
string input = "";
do
{
Console.WriteLine("Enter your number:");
input = Console.ReadLine();
if (input != ";")
sum += int.Parse(input);
} while (input != ";");
Console.WriteLine("Answer =" + sum);
break;
}
You are having problems because you should iterate the code until your exit/end condition is met using the while statement.
switch(exp)
{
case "+":
int mySum = 0;
string userInput = "";
while(userInput != ";")
{
Console.WriteLine("Enter number to add (';' to end the sum):");
userInput = Console.ReadLine();
if (userInput != ";")
{
// Would be interesting checking if entered really is an integer, for example Int32.TyParse()
mySum = mySum + Convert.ToInt32(userInput);
}
}
Console.WriteLine("Answer =" + mySum.ToString());
break;
}
Thankyou for your reply, but is there any way to auto the process, The program will ask for PlusA to PlusZ itself instead of int it my own
bool stayInLoop = true;
while(stayInLoop)
Console.WriteLine("Enter Yor Number");
var PlusA = Console.ReadLine();
Console.WriteLine("Enter Yor Number");
var PlusB = Console.ReadLine();
if(PlusA == ';')
{
stayInLoop = false;
break;
}
else if(PlusB == ';')
{
stayInLoop = false;
break;
}
else
{
Console.WriteLine("Answer =");
Console.WriteLine(PlusA + PlusB);
}
}
and when I run this, it run out 'error CS0019' and 'error CS0139'
What you're looking for is a while() loop.
example:
bool stayInLoop = true;
while(stayInLoop) // basically means (stayInLoop == true)
{
var text = Console.ReadLine();
if(text == ';')
{
stayInLoop = false;
break; // break will stop the loop, but you can also change the variable to false to break the loop.
}
}
Can someone help me make the option to quit the app at anytime work in this code? Also, I was wondering why I have to hit enter twice for the message "That is not an integer" when the user enters a string instead of a number?
using System;
using System.Threading;
namespace farino_HighLow
{
public class Game
{
// TAKES AND TRACKS USER INPUT
public void PlayGame()
{
// CREATES VARIABLE FOR INPUT FROM THE USER (IF THEY MAKE AN INVALID GUESS OR WANT TO EXIT),
// THE RANDOM VALUE GENERATED, THE USERS GUESS, AND A COUNTER FOR HOW MANY GUESSES THE USER TAKES
Random random = new Random();
int returnValue = random.Next(1, 100);
string input;
string line;
int guess = 0;
int count = 0;
Console.Beep(1000, 2000);
// INSTRUCTS USER WHAT TO DO
Console.WriteLine("Guess a number between 1-100");
Console.WriteLine("Hit Q at any time to exit the game");
do
{
input = Console.ReadLine();
try
{
guess = Convert.ToInt32(input);
}
catch
{
if (input == "Q")
{
break;
}
}
line = Console.ReadLine();
if (!int.TryParse(line, out guess))
Console.WriteLine("Not an integer!");
// MAKES SURE USER ENTERS A NUMBER WITHIN THE PARAMETERS OF THE GAME
// COUNTS THE USER GUESSES
// TELLS USER IF THEIR GUESS WAS RIGHT OR WRONG AND DIRECTS THEM TOWARDS A BETTER GUESS
if (guess >= 1 && guess <= 100)
{
if (guess > returnValue)
{
Console.Beep(100,2000);
Console.WriteLine("Guess Again! Your guess is too HIGH");
count += 1;
}
if (guess < returnValue)
{
Console.Beep(300,2000);
Console.WriteLine("Guess Again! Your guess is too LOW");
count += 1;
}
if (guess == returnValue)
{
Console.Beep(50,2000);
Console.Beep(60,2000);
Console.Beep(70,2000);
Console.WriteLine("You got it RIGHT!!!!!!");
count += 1;
Console.WriteLine("It took you" + count + "guesses to win the game.");
}
if (guess < 1)
{
Console.WriteLine("That is not a valid entry");
}
if (guess > 100)
{
Console.WriteLine("That is not a valid entry");
}
}
} while (guess != returnValue);
Thread.Sleep(5000);
Console.Clear();
}
}
}
Try This code
using System;
using System.Threading;
namespace farino_HighLow
{
public class Game
{
// TAKES AND TRACKS USER INPUT
public void PlayGame()
{
// CREATES VARIABLE FOR INPUT FROM THE USER (IF THEY MAKE AN INVALID GUESS OR WANT TO EXIT),
// THE RANDOM VALUE GENERATED, THE USERS GUESS, AND A COUNTER FOR HOW MANY GUESSES THE USER TAKES
Random random = new Random();
int returnValue = random.Next(1, 100);
string input;
string line;
int guess = 0;
int count = 0;
Console.Beep(1000, 2000);
// INSTRUCTS USER WHAT TO DO
Console.WriteLine("Guess a number between 1-100");
Console.WriteLine("Hit Q at any time to exit the game");
do
{
input = Console.ReadLine();
try
{
guess = Convert.ToInt32(input);
}
catch
{
if (input == "Q")
{
//after press Q exit from application
return;
}
}
line = Console.ReadLine();
if (!int.TryParse(line, out guess))
Console.WriteLine("Not an integer!");
// MAKES SURE USER ENTERS A NUMBER WITHIN THE PARAMETERS OF THE GAME
// COUNTS THE USER GUESSES
// TELLS USER IF THEIR GUESS WAS RIGHT OR WRONG AND DIRECTS THEM TOWARDS A BETTER GUESS
if (guess >= 1 && guess <= 100)
{
if (guess > returnValue)
{
Console.Beep(100, 2000);
Console.WriteLine("Guess Again! Your guess is too HIGH");
count += 1;
}
if (guess < returnValue)
{
Console.Beep(300, 2000);
Console.WriteLine("Guess Again! Your guess is too LOW");
count += 1;
}
if (guess == returnValue)
{
Console.Beep(50, 2000);
Console.Beep(60, 2000);
Console.Beep(70, 2000);
Console.WriteLine("You got it RIGHT!!!!!!");
count += 1;
Console.WriteLine("It took you" + count + "guesses to win the game.");
}
if (guess < 1)
{
Console.WriteLine("That is not a valid entry");
}
if (guess > 100)
{
Console.WriteLine("That is not a valid entry");
}
}
} while (guess != returnValue);
Thread.Sleep(5000);
Console.Clear();
}
}
}
Simply use either: Environment.Exit(0); or Application.Exit();
if(condition is true)
{
Environment.Exit(0);
}
else
{
//continue
}
I am trying to use a method to calculate the exchange rate then pass back that argument to the method in main. I am unsure if i have converted the money properly as i cant figure out what to put into the parameters when calling the method in main.
for example:
exchange(dont know what to put here);
Also unsure if i have done the exchange method correctly. The program runs up to the point of asking which currency the user whats to exchange to, but thats only when i comment out the exchange method. Really stuck, any tips?
I think i might have to assign values to each of the currencies SEK, USD ,EUR but not sure what to do from there...
Any help would be greatly appreciated!
(if i have enetered my code wrong on this question im sorry, not really sure how to make it look any cleaner)
----this is a console application----
class Program
{
static void Main(string[] args)
{
writeMenu();
//exchange();
//exchange(choiceFromCurrency, coiceToCurrency, valueToExchange);
Console.ReadKey();
}
public static void writeMenu()
{
Console.WriteLine("Welcome to your next level Currency Converter!");
Console.WriteLine("---We---Change---Your---Money---For---You---");
Console.WriteLine(" -------So---You---Dont---Have---To!-------\n\n");
Console.WriteLine("What is your base currency?\n");
Console.WriteLine("1 = SEK, 2= USD or 3= EUR?");
string userInput = Console.ReadLine();
if (userInput == "1")
{
Console.WriteLine("You have chosen SEK (Swedish Krona)\n");
}
else if (userInput == "2")
{
Console.WriteLine("You have chosen USD (United States Dollar)\n");
}
else
{
Console.WriteLine("You have chosen EUR (Euro)\n");
}
Console.WriteLine("Which currency would you like to change your money to?\n");
string userInput2 = Console.ReadLine();
if (userInput2 == "1")
{
Console.WriteLine("You have chosen SEK (Swedish Krona)\n");
}
else if (userInput2 == "2")
{
Console.WriteLine("You have chosen USD (United States Dollar)\n");
}
else
{
Console.WriteLine("You have chosen EUR (Euro)\n");
}
}
public static decimal exchange(decimal currencyToExchangeFrom, decimal currencyToExchangeTo )
{
Console.WriteLine("How much would you like to exchange?\n");
string amountToExchange = Console.ReadLine();
decimal amountToConvert = 0;
decimal.TryParse(amountToExchange, out amountToConvert);
decimal newValue;
// SEK
if(currencyToExchangeFrom == 1)
{
// SEK - SEK
if (currencyToExchangeTo == 1)
{
Console.WriteLine("You have your money, go spend it!");
}
// sek -usd
if (currencyToExchangeTo == 2)
{
newValue = amountToConvert / 8.50m;
Console.WriteLine("You now have" + newValue + " in USD");
}
}
//sek - eur
if(currencyToExchangeFrom == 2)
{
amountToConvert / 9.49m;
Console.WriteLine("You now have" + newValue + " in EUR");
}
// usd - eur
if (currencyToExchangeFrom == 3)
{
amountToConvert * 0.90m;
Console.WriteLine("You now have" + newValue + " in EUR");
}
Here's some ideas to get you going... I have a feeling this is homework, so I've only done some modest re-working.
static void Main(string[] args)
{
begin();
Console.ReadLine();
}
public static void begin()
{
Console.WriteLine("Welcome to your next level Currency Converter!");
Console.WriteLine("---We---Change---Your---Money---For---You---");
Console.WriteLine(" -------So---You---Dont---Have---To!-------\n\n");
Console.WriteLine("What is your base currency?\n");
Console.WriteLine("1 = SEK, 2= USD or 3= EUR?");
ConsoleKeyInfo keyPress = Console.ReadKey(true);
int uConvertFrom = getUserInput(keyPress);
if (uConvertFrom > -1)
{
switch (uConvertFrom)
{
case 1:
Console.WriteLine("You have chosen SEK (Swedish Krona)\n");
break;
case 2:
Console.WriteLine("You have chosen USD (United States Dollar)\n");
break;
case 3:
Console.WriteLine("You have chosen EUR (Euro)\n");
break;
}
}
else
{
if (uConvertFrom == -2)
{
//break;
}
else
{
Console.WriteLine("You didn't enter a valid response. Please try again");
begin();
}
}
Console.WriteLine("Which currency would you like to change your money to?\n");
keyPress = Console.ReadKey(true);
int uConvertTo = getUserInput(keyPress);
if (uConvertTo > -1) {
switch (uConvertTo)
{
case 1:
Console.WriteLine("You have chosen SEK (Swedish Krona)\n");
break;
case 2:
Console.WriteLine("You have chosen SEK (Swedish Krona)\n");
break;
case 3:
Console.WriteLine("You have chosen USD (United States Dollar)\n");
break;
case 4:
Console.WriteLine("You have chosen EUR (Euro)\n");
break;
}
}
else
{
if (uConvertFrom == -2)
{
//break;
}
else
{
Console.WriteLine("You didn't enter a valid response. Please try again");
begin();
}
}
exchange((decimal)uConvertFrom, (decimal)uConvertTo);
}
private static int getUserInput(ConsoleKeyInfo keyPress)
{
if (keyPress.Key == ConsoleKey.Escape)
{
Console.WriteLine("Thank you for using. Exiting now.");
return -2;
}
int ret = -1;
if (int.TryParse(keyPress.KeyChar.ToString(), out ret))
{
return ret;
}
else
{
return -1;
}
}
public static decimal exchange(decimal currencyToExchangeFrom, decimal currencyToExchangeTo)
{
Console.WriteLine("How much would you like to exchange?\n");
string amountToExchange = Console.ReadLine();
decimal amountToConvert = 0;
decimal.TryParse(amountToExchange, out amountToConvert);
decimal newValue = (decimal)0.000;
// SEK
if (currencyToExchangeFrom == 1)
{
// SEK - SEK
if (currencyToExchangeTo == 1)
{
Console.WriteLine("You have your money, go spend it!");
}
// sek -usd
if (currencyToExchangeTo == 2)
{
newValue = amountToConvert / 8.50m;
Console.WriteLine("You now have" + newValue.ToString("C2") + " in USD");
}
}
//sek - eur
if (currencyToExchangeFrom == 2)
{
amountToConvert /= 9.49m;
Console.WriteLine("You now have" + newValue.ToString("C2") + " in EUR");
}
// usd - eur
if (currencyToExchangeFrom == 3)
{
amountToConvert *= 0.90m;
Console.WriteLine("You now have" + newValue.ToString("C2") + " in EUR");
}
return (decimal).001;
}
I'm a newbie at C# and I'm having some difficulties writing a program that is going to let you save values in a variable, everything is working fine, except I can't save values into my variable. Here's the code:
while (true)
{
//Menu
Console.WriteLine (" \n\tWelcome!");
Console.WriteLine (" \t[1]Store value");
Console.WriteLine (" \t[2]Write message");
Console.WriteLine (" \t[3]Clear the console");
Console.WriteLine (" \t[4]Shut down program");
Console.Write("\tChoose: ");
//Users choice
int choice = Convert.ToInt32 (Console.ReadLine ());
//Users message
string usrMsg = null;
//if statement
if (choice == 1) {
usrMsg += Console.ReadLine ();
} else if (choice == 2) {
Console.WriteLine (usrMsg);
} else if (choice == 3) {
//Shuts down program
break;
} else if (choice == 4) {
//Clear program
Console.Clear ();
}
else
{
Console.WriteLine("please enter a number between 1-4");
}
}
You just move the usrMsg variable out of while block as a global the value will be saved.
//Users message
string usrMsg = null;
while (true)
{
//Menu
Console.WriteLine(" \n\tWelcome!");
Console.WriteLine(" \t[1]Store value");
Console.WriteLine(" \t[2]Write message");
Console.WriteLine(" \t[3]Clear the console");
Console.WriteLine(" \t[4SShut down program");
Console.Write("\tChoose: ");
//Users choice
int choice = Convert.ToInt32(Console.ReadLine());
//if statement
if (choice == 1)
{
usrMsg += Console.ReadLine();
}
else if (choice == 2)
{
Console.WriteLine(usrMsg);
}
else if (choice == 3)
{
//Shuts down program
break;
}
else if (choice == 4)
{
//Clear program
Console.Clear();
}
else
{
Console.WriteLine("please enter a number between 1-4");
}
}
When this runs it always creates userMsg as null. That means that at best it will 'save' only 1 value when the user chooses '1'. However, this will never get displayed if the user selects '2' as when the user gets to the menu again userMsg will have been set to null again.
My assumption is that you're trying to save the number of times someone has selected '1' and then display that if the user then hits option '2'.
Stick this:
//Users message
string usrMsg = null;
outside of the 'while' loop.