How to get variable totalCredit to increment properly - c#

In my program, I am supposed to have the user enter course selections, up to a max of 3. The problem I am running into is that in order for the switch to end at 3 courses, it has to update the value of totalCredit until it reaches 9 (which is a total of 3 courses worth 3 credits each). Basically, when you've already entered 3 courses and you try to enter a 4th, it should spit out case -3 from within the WritePrompt method, but it appears to not be changing the totalCredit variable at all.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleRegisterStudent
{
class Program
{
static void Main(string[] args)
{
(new Program()).run();
}
void run()
{
int choice;
int firstChoice = 0, secondChoice = 0, thirdChoice = 0;
int totalCredit = 0;
string yesOrNo = "";
System.Console.WriteLine("Teacher's Copy");
do
{
WritePrompt();
choice = Convert.ToInt32(Console.ReadLine());
switch (ValidateChoice(choice, firstChoice, secondChoice, thirdChoice, totalCredit))
{
case -1:
Console.WriteLine("Your entered selection {0} is not a recognized course.", choice);
break;
case -2:
Console.WriteLine("You have already registerd for this {0} course.", ChoiceToCourse(choice));
break;
case -3:
Console.WriteLine("You can not register for more than 9 credit hours.");
break;
case -4:
Console.WriteLine("Registration Confirmed for course {0}.", ChoiceToCourse(choice));
totalCredit += 3;
if (firstChoice == 0)
firstChoice = choice;
else if (secondChoice == 0)
secondChoice = choice;
else if (thirdChoice == 0)
thirdChoice = choice;
break;
}
WriteCurrentRegistration(firstChoice, secondChoice, thirdChoice);
Console.Write("\nDo you want to try again? (Y|N)? : ");
yesOrNo = (Console.ReadLine()).ToUpper();
} while (yesOrNo == "Y");
Console.WriteLine("Thank you for registering with us");
}
void WritePrompt()
{
Console.WriteLine("Please select a course for which you want to register by typing the number inside []");
Console.WriteLine("[1]IT 145\n[2]IT 200\n[3]IT 201\n[4]IT 270\n[5]IT 315\n[6]IT 328\n[7]IT 330");
Console.Write("Enter your choice : ");
}
int ValidateChoice(int choice, int firstChoice, int secondChoice, int thirdChoice, int totalCredit)
{
if (choice < 1 || choice > 7)
return -1;
else if (choice == firstChoice && choice == secondChoice && choice == thirdChoice)
return -2;
else if (totalCredit > 9)
return -3;
return -4;
}
void WriteCurrentRegistration(int firstChoice, int secondChoice, int thirdChoice)
{
if (secondChoice == 0)
Console.WriteLine("You are currently registered for {0}", ChoiceToCourse(firstChoice));
else if (thirdChoice == 0)
Console.WriteLine("You are currently registered for {0}, {1}", ChoiceToCourse(firstChoice), ChoiceToCourse(secondChoice));
else
Console.WriteLine("You are currently registered for {0}, {1}, {2}", ChoiceToCourse(firstChoice), ChoiceToCourse(secondChoice), ChoiceToCourse(thirdChoice));
}
string ChoiceToCourse(int choice)
{
string course = "";
switch (choice)
{
case 1:
course = "IT 145";
break;
case 2:
course = "IT 200";
break;
case 3:
course = "IT 201";
break;
case 4:
course = "IT 270";
break;
case 5:
course = "IT 315";
break;
case 6:
course = "IT 328";
break;
case 7:
course = "IT 330";
break;
default:
break;
}
return course;
}
}
}
No error messages, no build errors, it's the just program logic that isn't working.

When you've successfully entered 3 courses, totalCredit gets incremented by 3 for 3 times. Given its initial value of 0, the value of totalCredit while processing the 4th course entry would be 9
If you want to trigger the -3, you need to change:
else if (totalCredit > 9)
to:
else if (totalCredit >= 9)

Related

How to use loops instead of goto statement

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

how to return to the start of a switch statement after case complete

I have a console application in c# where I have to edit data inside a xml. This works so far I can get through id selection the dataset I want to edit and then edit single values. What I want to achieve is if the user gives an specific value after editing he/she should be able to go back a step back and edit other values of the same dataset.
For example: User edits the name of a customer with id 2 and wishes after saving the name to change adress. The application should be able to recognize the input from before and then just give the options of which the user can change the values again.
I tried calling the method inside the method but my application just finishes after saving the new value,
this is my code:
bool inputTester = true;
while (inputTester)
{
Console.WriteLine("Welche Seiner Daten möchten Sie verändern?");
Console.WriteLine("1) Für Vornamen");
Console.WriteLine("2) Für Nachnamen");
Console.WriteLine("3) für Adresse");
Console.WriteLine("4) für Geburtsdatum");
Console.WriteLine("5) für Bankdaten");
Console.WriteLine("Bitte geben Sie nun eine Option ein");
switch (Console.ReadLine())
{
case "1":
tgt = tempId;
var name = tgt.Descendants("firstName").FirstOrDefault();
Console.WriteLine("Bitte geben sie den neuen Vornamen ein");
name.Value = Console.ReadLine();
xDoc.Save(filepath);
Console.WriteLine("Kunde gespeichert");
Console.Clear();
Console.WriteLine("Möchten Sie weitere Daten dieses Kunden bearbeiten? Falls Ja drücken Sie 1");
if (Console.ReadLine().Equals(1))
break;
break;
I tried to do it in case 1 with calling the method inside it.
EDIT: I tried to do it with the while advices but still the outcome is the same. The program just finishes and then closes itself.
I reduced my code to the minimal state posible to try it localy. I hope this is fine like this.
Place the Switch Statement in a While(true) Loop and when you want to go back to the start of the loop use the:
Continue
statement, this will start the loop again.
And when you want to exit the loop just use:
Break
I will try to simplify your issue in order to illustrate the error you made.
The requirement is :
The program will ask for "1" or "2" and sum it till you give up and type "Stop".
Your attempt looked like this : It wont loop and only ask once.
static int Count_Original()
{
var num = 0;
Console.WriteLine("Original: How Many? (1/2)");
switch (Console.ReadLine())
{
case "1":
num += 1;
return num;
case "2":
num += 2;
return num;
}
return num;
}
If we had a loop: It will still not loop as the return make us quit the method.
static int Count_Loop()
{
var num = 0;
while (true)
{
Console.WriteLine("Loop: How Many? (1/2)");
switch (Console.ReadLine())
{
case "1":
num += 1;
return num;
case "2":
num += 2;
return num;
}
return num;
}
}
Simply removing the return won't fix it, we are now trap in the loop.
static int Count_Trap()
{
var num = 0;
while (true)
{
Console.WriteLine("Trap: How Many? (1/2)");
switch (Console.ReadLine())
{
case "1":
num += 1;
break;
case "2":
num += 2;
break;
default: // I didn't understand the input. Let me ask again.
break;
}
};
return num; // Never reach
}
The final version will look like this:
A break out option using return
a default in case we didn't type a valid option.
static int Count_Fix()
{
var num = 0;
while (true)
{
Console.WriteLine("Fix: How Many? (1/2)");
switch (Console.ReadLine())
{
case "Stop": // Breakout condition, we are leaving
return num;
case "1":
num += 1;
break;
case "2":
num += 2;
break;
default: // I didn't understand the input. Let me ask again.
break;
}
};
return num;
}
Finally if you wan't to have some conditional loop back or exit you can do it with a if/else:
static int Count_Fix()
{
var num = 0;
while (true)
{
Console.WriteLine("Fix: How Many? (1/2)");
switch (Console.ReadLine())
{
case "1":
num += 1;
break;
case "2":
num += 2;
if (num % 2 == 0) break; // conditional go back or exit
else return num; // exit
default: // I didn't understand the input. Let me ask again.
break;
}
};
}

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

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