How to use loops instead of goto statement - c#

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");
}
}

Related

Error detected trying to receive input as an integer in C#

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();
}

How do I create a terminable while loop in console application?

I am currently looking for a solution for this c# console application function
I tried searching for a method for creating a while loop that can terminate for the code below but I only came up with results relating to breaking while loops or the solution to be not to put it in a while loop
int P1Choice = int.Parse(Console.ReadLine());
while (true)
{
if (P1Choice == 1)
{
Console.WriteLine("");
CenterWrite("You have chosen Defult Empire 1");
break;
}
if (P1Choice == 2)
{
Console.WriteLine("");
CenterWrite("You have chosen Defult Empire 2");
break;
}
if (P1Choice == 3)
{
Console.WriteLine("");
CenterWrite("You have chosen Defult Empire 3");
break;
}
if (P1Choice == 4)
{
Console.WriteLine("");
CenterWrite("You have chosen Defult Empire 4");
break;
}
else
{
Console.WriteLine("");
CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
Console.ReadKey();
int P1Choice = int.Parse(Console.ReadLine());
}
}
I understand that I can't declare the local parameter "P1Choice" in this scope, but then are there any other methods to achieve the output of the code in such that when the user doesn't input the corresponding choices, that it loops again?
If you want to exit a while loop only when certain statements are met, then that's what you should state when entering your loop.
I would use a boolean to know whether the user made a right choice or not.
bool right_choice = false;
int P1Choice = int.Parse(Console.ReadLine());
while(!right_choice) {
switch(P1Choice) {
case 1:
right_choice = true;
{case 1 code};
break;
case 2:
right_choice = true;
{case 2 code};
break;
case 3:
right_choice = true;
{case 3 code};
break;
case 4:
right_choice = true;
{case 4 code};
break;
default:
break;
}
if (!right_choice) {
Console.WriteLine("");
CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
Console.ReadKey();
P1Choice = int.Parse(Console.ReadLine());
}
}
}
This way as soon as the user makes a correct choice you exit the loop.
Note that I changed your code to use a switch case instead of 4 ifs, since this would be the accepted way of implementing user input choice.
Good luck!
You just have to use readline inside your while loop and in else also do break. It should work this way:
int P1Choice;
while (true)
{
P1Choice = int.Parse(Console.ReadLine());
if (P1Choice == 1)
{
Console.WriteLine("");
CenterWrite("You have chosen Defult Empire 1");
break;
}
if (P1Choice == 2)
{
Console.WriteLine("");
CenterWrite("You have chosen Defult Empire 2");
break;
}
if (P1Choice == 3)
{
Console.WriteLine("");
CenterWrite("You have chosen Defult Empire 3");
break;
}
if (P1Choice == 4)
{
Console.WriteLine("");
CenterWrite("You have chosen Defult Empire 4");
break;
}
else
{
Console.WriteLine("");
CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
break;
}
}
I hope this is what you need. The possibles values are in the List "list" and it loops until the answer is one of the possible values:
int value = 0;
List<int> list = new List<int> { 1, 2, 3, 4 }; // choices are in the list
while (true)
{
Console.WriteLine("Please enter a number :");
if (int.TryParse(Console.ReadLine(), out value))
{
if (list.Contains(value))
break;
}
}
// value is in the list, deal with it.
One option can be to create method and keep calling until valid input comes:
public static void ProcessInput(string input)
{
int choice = Convert.ToInt32(input);
switch (choice)
{
case 1:
Console.WriteLine("");
Console.WriteLine("You have chosen Defult Empire 1");
break;
case 2:
Console.WriteLine("");
Console.WriteLine("You have chosen Defult Empire 2");
break;
case 3:
Console.WriteLine("");
Console.WriteLine("You have chosen Defult Empire 3");
break;
case 4:
Console.WriteLine("");
Console.WriteLine("You have chosen Defult Empire 4");
break;
default:
Console.WriteLine("");
Console.WriteLine("Input Invalid, Please press the number from the corresponding choices to try again");
ProcessInput(Console.ReadLine());
break;
}
and in your main program:
public static void Main()
{
Console.WriteLine("Hello World");
ProcessInput(Console.ReadKey());
}
You can do the following
var options = new Dictionary<int, Action> {
{1, () => {
//opt 1 code
}},
{2, () => {
//opt 2 code
}},
{3, () => {
//opt 3 code
}},
{4, () => {
//opt 4 code
}}
};
Console.WriteLine("Please enter you choice:");
int P1Choice;
while (!(int.TryParse(Console.ReadLine(), out P1Choice) && options.ContainsKey(P1Choice)))
{
Console.WriteLine("Input Invalid, Please press the number from the corresponding choices to try again:");
}
options[P1Choice]();
Here is code based on the post you deleted :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
BattleGrid grid = new BattleGrid();
grid.PrintGrid();
Console.ReadLine();
}
}
public class BattleGrid
{
public List<List<BattleGridCell>> grid = new List<List<BattleGridCell>>();
public BattleGrid()
{
for (int row = 0; row < 4; row++)
{
List<BattleGridCell> newRow = new List<BattleGridCell>();
grid.Add(newRow);
for (int col = 0; col < 4; col++)
{
BattleGridCell newCell = new BattleGridCell();
newRow.Add(newCell);
newCell.rowLetter = ((char)((int)'A' + row)).ToString();
newCell.colnumber = col.ToString();
}
}
}
public void PrintGrid()
{
foreach (List<BattleGridCell> row in grid)
{
Console.WriteLine("|" + string.Join("|", row.Select(x => "X" + x.rowLetter + x.colnumber)));
}
}
}
public class BattleGridCell
{
public string rowLetter { get; set; }
public string colnumber { get; set; }
}
}
You have 2 problems:
1. Your code doesn't compile because you try to bind P1Choice twice.
2. You ask for input twice in your else case.
To fix 1., you have to remove int from the second occurrence of P1Choice, the one in the else case.
To fix 2., you have to remove Console.readKey() in the else case.
Besides, your code will be easier to read if you use else if clauses instead of just if clauses.
while (true) {
int P1Choice = int.Parse(Console.ReadLine());
if (P1Choice == 1) {
Console.WriteLine("");
CenterWrite("You have chosen Default Empire 1");
} else if (P1Choice == 2) {
Console.WriteLine("");
CenterWrite("You have chosen Default Empire 2");
} else if (P1Choice == 3) {
Console.WriteLine("");
CenterWrite("You have chosen Default Empire 3");
} else if (P1Choice == 4) {
Console.WriteLine("");
CenterWrite("You have chosen Default Empire 4");
} else {
Console.WriteLine("");
CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
}
}
Furthermore, I'd recommend you to use a switch clause instead of this many if clauses. But let that be a lecture for another day. :)
You can make further improvements.
In all cases, you call Console.WriteLine("") so move it outside.
while (true) {
int P1Choice = int.Parse(Console.ReadLine());
Console.WriteLine("");
if (P1Choice == 1) {
CenterWrite("You have chosen Default Empire 1");
} else if (P1Choice == 2) {
CenterWrite("You have chosen Default Empire 2");
} else if (P1Choice == 3) {
CenterWrite("You have chosen Default Empire 3");
} else if (P1Choice == 4) {
CenterWrite("You have chosen Default Empire 4");
} else {
CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
}
}
Instead of having fixed Strings, you can concatenate the value of P1Choice.
while (true) {
int P1Choice = int.Parse(Console.ReadLine());
Console.WriteLine("");
if (1 <= P1Choice && P1Choice <= 4) {
CenterWrite("You have chosen Default Empire " + P1Choice);
} else {
CenterWrite("Input Invalid, Please press the number from the corresponding choices to try again");
}
}

Avoid goto statement in C#

I don't want to use some sort of goto statement, but I want the user to return to the main menu when the default case is executed. How?? I know this is a simple problem, but there must be lots of newbie who come across something very similar.
static void buycoffee()
{
Double price = 0;
int x = 0;
while (x == 0)
{
Console.WriteLine("Pick a coffee Size");
Console.WriteLine("1: Small");
Console.WriteLine("2: Medium");
Console.WriteLine("3: Large");
int Size = int.Parse(Console.ReadLine());
switch (Size)
{
case 1:
price += 1.20;
break;
case 2:
price += 1.70;
break;
case 3:
price += 2.10;
break;
default:
Console.WriteLine("This option does not exist");
///how to return to the main menu here
break;
}
Console.WriteLine("Would you like to buy more coffee?");
String Response = Console.ReadLine().ToUpper();
if (Response.StartsWith("Y"))
{
Console.Clear();
}
else
{
x += 1;
}
}
Console.WriteLine("The total bill comes to £{0}", price.ToString("0.00"));
}
}
replace your commented line with: continue;
As Nico Schertier said, you can accomplish this with something like the following:
int Size = -1;
while (Size == -1) {
Console.WriteLine("Pick a coffee Size");
Console.WriteLine("1: Small");
Console.WriteLine("2: Medium");
Console.WriteLine("3: Large");
Size = int.Parse(Console.ReadLine());
switch (Size)
{
case 1:
price += 1.20;
break;
case 2:
price += 1.70;
break;
case 3:
price += 2.10;
break;
default:
Size = -1;
Console.WriteLine("This option does not exist");
break;
}
}
Beside #Abion47 and #Dogu Arslan's answers you can also create a function for your menu and also one for your switch.
In this example it will create an infinite loop menu
static void Menu()
{
Console.WriteLine("Menu");
Console.WriteLine("1) Take me to My fancy menu");
}
static void SwitchFunc(string input)
{
switch (input)
{
case "1":
Menu();
string inputB = Console.ReadLine();
SwitchFunc(inputB);
break;
}
}
static void Main(string[] args)
{
Menu();
string input = Console.ReadLine();
SwitchFunc(input);
}

C# - Tryinig to do exchange rates in if/else statement and pass argument into method parameters in main function

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;
}

the switch case block after final score is outputed, is not compiling [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
it doesnt show the IQ result after the final score has been shown. please help. this is the full program...i used an arrow to show the switch block that refuses to compile
class Class1
{
public static int attempt, sum, AptScore, GenScore, MathScore, EngScore, bonus, TotalScore, FinalScore, choice = 0;
public static string ans;
static void Main(string[] args)
{
int FinalCount, AptCount = 0, EngCount = 0, MathCount = 0, GenCount = 0;
Console.WriteLine("Welcome to Salisbury University IQ Test game \n=====================================");
Console.WriteLine();
Console.WriteLine("How many times have you attempted this test?");
attempt = Convert.ToInt32(Console.ReadLine());
while (true)
{
if (attempt > 1)
{
Console.WriteLine("You cannot take this test");
break;
}
while (true)
{
FinalCount = AptCount + EngCount + MathCount + GenCount;
if (FinalCount < 4)
{
Console.WriteLine("Salisbury University IQ Test game \n========================================");
Console.WriteLine("Press \n1. Aptitude \n2. English. \n3. Math \n4. Gk \n5. Exit");
choice = Convert.ToInt32(Console.ReadLine());
switch (choice)
{
case 1:
if (AptCount > 0)
{
Console.WriteLine("THIS QUESTION HAS BEEN ATTEMPTED!!!");
Console.WriteLine();
continue;
}
Console.WriteLine(" What was the name of the lebanon tyrant who ruled for years unending before he was toppled due to civil war? \nA. Osama Bin laden \nB. Gaddafi \nC. Jonathan ");
ans = Console.ReadLine();
if (ans == "B" || ans == "b")
{
AptScore += 10;
}
AptCount++;
continue;
case 2:
if (EngCount > 0)
{
Console.WriteLine("THIS QUESTION HAS BEEN ATTEMPTED!!!");
Console.WriteLine();
continue;
}
Console.WriteLine(" What is the antonym of Pleasure? \nA. Pain \nB. Ecstacy \nC. Wonder");
ans = Console.ReadLine();
if (ans == "A" || ans == "a")
{
EngScore += 10;
}
EngCount++;
continue;
case 3:
if (MathCount > 0)
{
Console.WriteLine("THIS QUESTION HAS BEEN ATTEMPTED!!!");
Console.WriteLine();
continue;
}
Console.WriteLine(" What is the sum of 435 and 345? \nA. 799 \nB. 780 \nC. 600 ");
ans = Console.ReadLine();
if (ans == "B" || ans == "b")
{
MathScore += 10;
}
MathCount++;
continue;
case 4:
if (GenCount > 0)
{
Console.WriteLine("THIS QUESTION HAS BEEN ATTEMPTED!!!");
Console.WriteLine();
continue;
}
Console.WriteLine(" What year did Nigeria become a republic? \nA. 1960 \nB. 1963 \nC. 1990 ");
ans = Console.ReadLine();
if (ans == "B" || ans == "b")
{
GenScore += 10;
}
GenCount++;
continue;
case 5:
Environment.Exit(0);
break;
default:
Console.WriteLine("You entered an invalid number");
continue;
} // end of switch
break;
} // end of inner while loop
break;
} // end of else
break;
} // outer loop end
if (attempt < 5 && attempt != 0)
{
TotalScore = MathScore + GenScore + EngScore + AptScore;
Console.WriteLine("Your total score is : " + TotalScore);
if (TotalScore == 10)
{
Console.WriteLine(" You have no Bonus point ");
}
else if (TotalScore == 20)
{
bonus += 2;
Console.WriteLine("Your Bonus is {0}", bonus);
}
else if (TotalScore == 30)
{
bonus += 5;
Console.WriteLine("Your Bonus is {0}", bonus);
}
else if (TotalScore == 40)
{
bonus += 10;
Console.WriteLine("Your Bonus is {0}", bonus);
}
FinalScore = TotalScore + bonus;
Console.WriteLine("Your finalscore is : " + FinalScore);
**it refuses to compile this switch block -->** switch (FinalScore)
{
case 10:
if (FinalScore >= 10)
{
Console.WriteLine("Your IQ level is below average");
}
break;
case 22:
if (FinalScore >= 22)
{
Console.WriteLine("Your IQ level is average");
}
break;
case 35:
if (FinalScore >= 35)
{
Console.WriteLine("You are intelligent");
}
break;
case 40:
if (FinalScore == 40)
{
Console.WriteLine("You are a genius");
}
break;
default:
break;
} // end of last s1witch case
}// end of if statement
} // end of main method */
} // end of class
Its always better to use if/else for your particular case, With switch statement you can't put conditions in the case. It looks like you are checking for ranges and if the range is constant then you can try the following
if (FinalScore == 40)
{
Console.WriteLine("You are a genius");
}else if (FinalScore >= 35)
{
Console.WriteLine("You are intelligent");
}else if (FinalScore >= 22)
{
Console.WriteLine("Your IQ level is average");
}else if(FinalScore >= 10)
{
Console.WriteLine("Your IQ level is below average");
}else
{
// something else
}
You should use If else statements for what you are trying to do and you could shorten your code a whole lot by making use of ternary statements like so,
Console.WriteLine((FinalScore >= 40) ? "You are a genius" :
(FinalScore >= 35) ? "You are intelligent" :
(FinalScore >= 22) ? "Your IQ level is average" :
(FinalScore >= 10) ? "Your IQ level is below average" : "You are really below average");
//The really below average would be your something else referenced above.
Your code compiles just fine.
If you logged the default case of that switch block, you would've seen that 40 is effectively an unreachable case. Your formula guarantees that 40 is never generated -- all 4 correct is 50 points due to the bonus points. All incorrect would also never yield a result.
The valid cases are: 0, 10, 22, 35, 50. You only account for 10, 22, & 35.
default:
// this would've thrown an exception for FinalScore==50
throw new Exception("unexpected score of " + FinalScore);

Categories

Resources