Not using the else - c#

I'm try to not use the else in the code and just the if. But when I run it and enter "Q" it say error of converting in the total += Convert.ToInt32(input);. Is there a way around this?
do
{
Console.Clear();
Console.WriteLine("Enter a number or Q to quit", input);
input = Console.ReadLine();
if (input.ToUpper() == "Q")
{
Console.WriteLine("Press any key to continue");
Console.ReadKey();
}
else
{
total += Convert.ToInt32(input);
numbersEntered++;
average = ((double)total / numbersEntered);
Console.WriteLine("Total: {0}\t Numbers Entered: {1}\t Average: {2}\t", total, numbersEntered, average);
Console.ReadKey();
}
}
while (input.ToUpper() != "Q");

Try using break; to stop the loop so you don't need the else.
do{
Console.Clear();
Console.WriteLine("Enter a number or Q to quit", input);
input = Console.ReadLine();
if (input.ToUpper() == "Q"){
Console.WriteLine("Press any key to continue");
Console.ReadKey();
break;
}
total += Convert.ToInt32(input);
numbersEntered++;
average = ((double)total / numbersEntered);
Console.WriteLine("Total: {0}\t Numbers Entered: {1}\t Average: {2}\t", total, numbersEntered, average);
Console.ReadKey();
} while (input.ToUpper() != "Q");

Use TryParse to test if the input is a numeric. Here's an example for int (you'll need to define the out variable yourself).
else if (Int32.TryParse(input,out inputVal) {

Related

How to go back from a switch? c#

After I've added credits I want it to go back to display the main menu again. What is the way to do this? And is there an easier way? I am not very experienced in programming.
Console.WriteLine("-------------------------------");
Console.WriteLine("");
Console.WriteLine(" VENDING MACHINIES LTD");
Console.WriteLine("");
Console.WriteLine("-------------------------------");
Console.WriteLine(" Main Menu");
Console.WriteLine("");
Console.WriteLine("1 - Add Credits (current credits= 0.00)");
Console.WriteLine("2 - Select product/s");
Console.WriteLine("3 - Exit");
Cons
Try this code:
var returnBack = true;
do
{
Console.WriteLine("-------------------------------");
Console.WriteLine("");
Console.WriteLine(" VENDING MACHINIES LTD");
Console.WriteLine("");
Console.WriteLine("-------------------------------");
Console.WriteLine(" Main Menu");
Console.WriteLine("");
Console.WriteLine("1 - Add Credits (current credits= 0.00)");
Console.WriteLine("2 - Select product/s");
Console.WriteLine("3 - Exit");
Console.WriteLine("");
Console.Write("Please Enter A Number: ");
choice = Convert.ToInt32(Console.ReadLine());
while (choice < 1 || choice > 3)
{
Console.Write("Incorrect option. Please Re-Enter: ");
choice = Convert.ToInt32(Console.ReadLine());
}
switch (choice)
{
case 1:
Console.Write("How Many Credits Would You Like To Add? ");
credits = Convert.ToInt32(Console.ReadLine());
Console.Write("You Now Have {0} Credits", credits);
Console.WriteLine("");
Console.Write("Press return to go back to the main menu");
Console.ReadLine();
break;
case 2:
Console.WriteLine();
break;
case 3:
returnBack=false;
break;
}
} while (returnBack);
You can use while(true) for eternity cycle of menu and return for exit from your application
Console.WriteLine("-------------------------------");
Console.WriteLine("");
Console.WriteLine(" VENDING MACHINIES LTD");
Console.WriteLine("");
Console.WriteLine("-------------------------------");
while(true)
{
Console.WriteLine(" Main Menu");
Console.WriteLine("");
Console.WriteLine("1 - Add Credits (current credits= 0.00)");
Console.WriteLine("2 - Select product/s");
Console.WriteLine("3 - Exit");
Console.WriteLine("");
Console.Write("Please Enter A Number: ");
choice = Convert.ToInt32(Console.ReadLine());
while (choice < 1 || choice > 3)
{
Console.Write("Incorrect option. Please Re-Enter: ");
choice = Convert.ToInt32(Console.ReadLine());
}
switch (choice)
{
case 1:
Console.Write("How Many Credits Would You Like To Add? ");
credits = Convert.ToInt32(Console.ReadLine());
Console.Write("You Now Have {0} Credits", credits);
Console.WriteLine("");
Console.Write("Press return to go back to the main menu");
Console.ReadLine();
break;
case 2:
Console.WriteLine();
break;
case 3:
Console.WriteLine("Bye-bye");
return;
}
}
You can use a recursive method and I would also suggest to extract the "menu" console write lines. Please have a look on the following:
static void Main(string[] args)
{
DisplayMenu();
var choice = Convert.ToInt32(Console.ReadLine());
// Final response
choice = DisplayMenu(choice);
}
public static void DisplayMenu()
{
Console.WriteLine(" Main Menu");
Console.WriteLine("");
Console.WriteLine("1 - Add Credits (current credits= 0.00)");
Console.WriteLine("2 - Select product/s");
Console.WriteLine("3 - Exit");
Console.WriteLine("");
Console.Write("Please Enter A Number: ");
}
// Recursive overload
public static int DisplayMenu(int choice)
{
// If invalid input
if (choice<1 || choice>3)
{
Console.Write("Incorrect option. Please Re-Enter: ");
Console.WriteLine();
DisplayMenu();
return DisplayMenu(Convert.ToInt32(Console.ReadLine()));
}
// If valid show one more time the menu
DisplayMenu();
return Convert.ToInt32(Console.ReadLine());
}

using continue and break statements properly for a game

I have to make a card game like HiLo where you enter your cash amount, you get two cards, and then you bet. if the third randomly generated card is between the other two, you add that money to your total and if its not you lose that money. One thing the code is supposed to do is if you don't like the two cards you are given at the beginning you should be able to enter 0 and they give you new cards. My biggest problem comes from when I enter 0 it gives me two new cards and then asks how much I want to put up and when I enter that number it basically ignores the new bet money and asks me again. essentially i have to write twice the betmoney for it to work, how do I fix that.
using System;
//find how to print dollar signs
class MainClass {
public static void Main (string[] args) {
var rnd = new Random();
int card1, card2, card3;
int playermoney = 0;
int betmoney = 0;
string exit = "";
Console.WriteLine("HiLo Card Game");
Console.Write("Enter the starting cash amount: $");
playermoney = Convert.ToInt32(Console.ReadLine());
while(exit!="n"){
card1 = rnd.Next(1,15);
card2 = rnd.Next(1,15);
Console.WriteLine("Cash balance is ${0}",playermoney);
Console.WriteLine("{0} - {1}", card1, card2);
Console.Write("The amount you want to bet? ");
betmoney = Convert.ToInt32(Console.ReadLine());
if (betmoney>=0){
if (betmoney == 0){
Console.WriteLine("Cash balance is ${0}",playermoney);
Console.WriteLine("{0} - {1}", rnd.Next(1,15), rnd.Next(1,15));
Console.Write("The amount you want to bet? ");
betmoney = Convert.ToInt32(Console.ReadLine());
continue;
}//end if 0
card3 = rnd.Next(1,15);
Console.WriteLine("Your card is a {0}", card3);
if(card1<card2){
if((card3>card1 && card3<card2)){
playermoney = playermoney+betmoney;
Console.WriteLine("WINNER! New Balance is {0}", playermoney);
}//end winner if
else{
playermoney = playermoney-betmoney;
Console.WriteLine("LOSER! New Balance is {0}", playermoney);
if (playermoney<0){
Console.WriteLine("--------------");
Console.WriteLine("game over");
break;
}//end negative if
}//end else loser
}
if (card1>card2){
if(card3>card2 && card3<card1){
playermoney = playermoney+betmoney;
Console.WriteLine("WINNER! New Balance is {0}", playermoney);
}
else{
playermoney = playermoney-betmoney;
Console.WriteLine("LOSER! New Balance is {0}", playermoney);
if (playermoney<0){
Console.WriteLine("--------------");
Console.WriteLine("game over");
break;
}//end negative if
}//end else loser
}
}
else{
Console.WriteLine("--------------");
Console.WriteLine("game over");
break;
}
Console.Write("Play Again? <y/n> ");
exit = Console.ReadLine();
Console.Clear();
}
}
}
I think what you want to do is continue right away if the betAmount is 0 (or less than zero), rather than trying to pick new cards again inside the main loop:
if (betMoney < 1) continue;
Some other thoughts:
Additionally, you should use int.TryParse to parse the integer input because Convert.ToInt32 will throw an exception if the input is not a valid integer. This way we can use TryParse as an if condition and continue to ask them for a valid number.
Random should almost always be declared as a class field rather than a local variable. In this case it doesn't matter, but it's a good habit to get into.
We can use Math.Max and Math.Min to determine which of the two random cards are the largest and smallest, to avoid the repetitive code (the code in the if (card1 > card2) block is repeated for card2 > card1)
We can use Math.Abs to determine the absolute value of the difference of card1 and card2, so if they are the same card or are sequential, we can just continue the loop (there is no chance to win in those cases).
We can move the Console.Clear inside the loop so after they enter the initial playerMoney amount, we always see the same screen while playing.
We can use Console.ReadKey() to get a single key from the user (for y/n), and then use the .Key property to determine if it's an n or N.
Here's some code with these ideas implemented:
private static Random rnd = new Random();
static void Main()
{
Console.WriteLine("HiLo Card Game");
Console.WriteLine("--------------");
Console.Write("Enter the starting cash amount: $");
int playerMoney;
while (!int.TryParse(Console.ReadLine(), out playerMoney) ||
playerMoney < 1)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("Please enter a positive number for cash amount: $");
Console.ResetColor();
}
while (true)
{
// Draw two random cards
int card1 = rnd.Next(1, 15);
int card2 = rnd.Next(1, 15);
// Start the loop again if there is not at least
// one card available between card1 and card2
if (Math.Abs(card1 - card2) < 2) continue;
// Determine the min and max of the two random cards
var minCard = Math.Min(card1, card2);
var maxCard = Math.Max(card1, card2);
Console.Clear();
Console.WriteLine("HiLo Card Game");
Console.WriteLine("--------------");
Console.WriteLine("Cash balance is: ${0}", playerMoney);
Console.WriteLine("{0} - {1}", minCard, maxCard);
Console.Write("Enter the amount you want to bet: $");
int betMoney;
while (!int.TryParse(Console.ReadLine(), out betMoney))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("Please enter a valid number for bet amount: $");
Console.ResetColor();
}
// If the bet amount is negative or 0, restart
// the loop so they can get new cards
if (betMoney < 1) continue;
// Draw a card for the player
int playerCard = rnd.Next(1, 15);
Console.WriteLine("Your card is: {0}", playerCard);
// If the players card is between the random cards, they win
if (playerCard < maxCard && playerCard > minCard)
{
playerMoney += betMoney;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("WINNER! New Balance is ${0}", playerMoney);
Console.ResetColor();
}
else
{
playerMoney -= betMoney;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("LOSER! New Balance is ${0}", playerMoney);
Console.ResetColor();
if (playerMoney <= 0)
{
Console.WriteLine("--------------");
Console.Write("Game over. Press any key to exit...");
Console.ReadKey();
break;
}
}
Console.Write("Play Again? <y/n>: ");
if (Console.ReadKey().Key == ConsoleKey.N) break;
}
}

Invalid expression term 'else' after i typed it the second time

static void Main(string[] args)
{
Console.WriteLine("what is the value of 3 + 8?");
number = int.Parse(Console.ReadLine());
if (number == 11)
{
Console.WriteLine("well done");
Console.WriteLine("press enter once");
Console.ReadLine();
}
else;
{
Console.WriteLine("its 11 u idiot!!!");
Console.ReadLine();
}
Console.WriteLine("what is the value of 23132-23131?");
number = int.Parse(Console.ReadLine());
if (number == 1);
{
Console.WriteLine("oh yeah!");
Console.ReadLine();
}
else;
{
Console.WriteLine("u r such a noob!");
Console.ReadLine();
}
}
What is the problem there??? Visual studio told me invalid expression term 'else' after the second 'else' i typed and i don't know why?
Remove the semicolon after each of the two else keywords:
else // was else;
and after the if line:
if (number == 1) // was if (number == 1);
In addition, you should actually declare number:
var number = int.Parse(Console.ReadLine());
This is the final version of code that should work:
static void Main(string[] args)
{
Console.WriteLine("what is the value of 3 + 8?");
var number = int.Parse(Console.ReadLine());
if (number == 11)
{
Console.WriteLine("well done");
Console.WriteLine("press enter once");
Console.ReadLine();
}
else
{
Console.WriteLine("its 11 u idiot!!!");
Console.ReadLine();
}
Console.WriteLine("what is the value of 23132-23131?");
number = int.Parse(Console.ReadLine());
if (number == 1)
{
Console.WriteLine("oh yeah!");
Console.ReadLine();
}
else
{
Console.WriteLine("u r such a noob!");
Console.ReadLine();
}
}
Do it like this
int number;
Console.WriteLine("what is the value of 3 + 8?");
number = int.Parse(Console.ReadLine());
if (number == 11)
{
Console.WriteLine("well done");
Console.WriteLine("press enter once");
Console.ReadLine();
}
else
{
Console.WriteLine("its 11 u idiot!!!");
Console.ReadLine();
}
Console.WriteLine("what is the value of 23132-23131?");
number = int.Parse(Console.ReadLine());
if (number == 1)
{
Console.WriteLine("oh yeah!");
Console.ReadLine();
}
else
{
Console.WriteLine("u r such a noob!");
Console.ReadLine();
}

need help on creating a counter with a total, number enter, and average

The requirement are:
create an application that will allow the user to enter numbers and
provide the average of the numbers entered. The user will be allowed to enter as many numbers as they choose. After each entry we will display the current average.
Keep repeating until the user decides to quit.
I want to user to keep entering number until they type "q" to quit. Please help.
string input = "";
int numbersEntered = 0;
int average = 0;
int total = 0;
do
{
Console.Clear();
Console.WriteLine("Enter a number or Q to quit", input);
input = Console.ReadLine();
total += Convert.ToInt32(input);
average = (total / numbersEntered);
Console.WriteLine("Total: {0}\t Numbers Entered: {1}\t Average: {2}\t", total, numbersEntered++, average);
}
while (input.ToUpper() == "Q");
{
Console.WriteLine("Press any key to continue");
Console.ReadKey();
}
Console.ReadKey();
Put the Console.ReadLine inside the loop -- and put the writing of the total/average after calculating those numbers.
Also, you might want to validate the input, instead of assuming it is a number -- use int.TryParse.
do
{
Console.WriteLine("Enter a number of Q to quit", input);
input = Console.ReadLine();
int val;
if (int.TryParse(input, out val))
{
total += val;
average = (total / numbersEntered);
Console.WriteLine("Total: {0}\t Numbers Entered: {1}\t Average: {2}\t", total, numbersEntered++, average);
}
}
while (input.ToUpper() != "Q");
There are three points needs to be corrected.
numbersEntered is 0 in the first calculation. You should pre-increment it while dividing by it.
also in the condation of while loop, it should be input.ToUpper() != "Q" instead of input.ToUpper() == "Q".
After correcting above two things your current code is calculating the average but it clearing the console after printing it. So, you should want after printing it by Console.Read();
Following is the code corrected:
string input = "";
int numbersEntered = 0;
int average = 0;
int total = 0;
do
{
Console.Clear();
Console.WriteLine("Enter a number or Q to quit", input);
input = Console.ReadLine();
int valueEntered;
if (int.TryParse(input, out valueEntered))
{
total += valueEntered;
average = (total / ++numbersEntered);
Console.WriteLine("Total: {0}\t Numbers Entered: {1}\t Average: {2}\t", total, numbersEntered, average);
Console.ReadKey();
}
}
while (input.ToUpper() != "Q");
Console.WriteLine("Press any key to continue");
Console.ReadKey();
Simply a typo(?) Your while needs to be:
...
while (input.ToUpper() != "Q");
That is != instead of ==.
Minimalistic solution:
int nTotal = 0;
double avg = 0;
string input;
while ((input = Console.ReadLine()).ToUpper() != "Q")
{
int number = int.Parse(input);
avg += (number-avg) / ++nTotal;
Console.WriteLine("Total numbers entered: {0}. Average: {1}", nTotal, avg);
}

simple temperature conversion questions

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

Categories