c#....my while loop keep repeating [duplicate] - c#

This question already exists:
c# programming constructs - my while loop wont stop working when i want it to? [closed]
Closed 9 years ago.
i am trying to get my while loop to ONLY keep repeating till all subjects have been answered, then it should stop and display the bonus and final score. but don't know why its not doing that? help please.
namespace Assignment
{
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)
{
bool stop = false;
Console.WriteLine("Welcome to this Salisbury University IQ Test game");
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");
}
else
{
Console.WriteLine(" \n1. Aptitude \n2. English. \n3. Math \n4. Gk \n5. Exit");
choice = Convert.ToInt32(Console.ReadLine());
switch (choice)
{
case 1:
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;
}
break;
case 2:
Console.WriteLine(" What is the antonym of Pleasure? \nA. Pain \nB. Ecstacy \nC. Wonder");
ans = Console.ReadLine();
if (ans == "A" || ans == "a")
{
EngScore += 10;
}
break;
case 3:
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;
}
break;
case 4:
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;
}
break;
case 5:
Environment.Exit(0);
break;
}
if (stop)
break;
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);
}
else
{
FinalScore = TotalScore + bonus;
Console.WriteLine("Your finalscore is : " + FinalScore);
}
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;
}
}
}
}
}

if (stop)
break;
This never happens.

I see:
bool stop = false;
and also:
if (stop)
break;
But I never see a stop = true;
Where do you intend to set stop to true?

Related

C# | Initialized array gives System.NullReferenceException

I am currently making a lottery simulator in C# but now that I wanted to make a feature to let the User randomize their lottery numbers instead of having to write them manually using arrays, but it gives me the Error Code:
Exception thrown
System.NullReferenceException: 'Object reference not set to an instance of an object.'
I declared and initialized my array named "randomList" for the random numbers like this:
public static int[] randomList = new int[5];
After I wanted to write the code that stores the 6 random numbers the user got in the array:
Console.WriteLine("\nRandomized 6 numbers: ");
for (int z = 0; z <= 6; z++)
{
int rndNum = rnd.Next(1, 50);
randomList[z] = rndNum; // <-- ERROR
Console.Write(rndNum + ", ");
}
I thought that you would only get that Error if you haven't initialized your variable or array. I would love someone explain the error to me and how to avoid/fix it! Thanks!
Here you can access the entire code (Error in line 203):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Lottery
{
internal class Program
{
// Global Variables:
// Playing
public static int playoption;
public static int betoption;
public static int gameAmount;
public static int gameCost = 10;
public static int superNumCost = 5;
public static string includeSuperNum;
public static int tickets;
public static int superNumTickets;
// Used for the Lotto Numbers
public static int[] correctList = new int[5];
public static int[] randomList = new int[5];
public static int[] manualList = new int[5];
// Indicators if you have correct numbers
public static int userCorrect;
public static int userSuperCorrect;
// Bank
public static int bankoption;
public static int deposit;
public static int withdrawal;
public static int balance = 0;
public static int cash = 300;
static void Main()
{
// Variables
// Menu
int menuoption;
Console.Clear();
Console.WriteLine("=== LOTTO! 6 out of 49 ===");
Console.WriteLine(" 1. Play");
Console.WriteLine(" 2. Bank Menu");
Console.WriteLine(" 3. Go work");
Console.WriteLine(" 4. Quit");
WrongMenu:
Console.Write("\nEnter your option by typing out the number: ");
menuoption = Convert.ToInt32(Console.ReadLine());
switch (menuoption)
{
case 1:
PlayMenu();
break;
case 2:
Bank();
break;
case 3:
Work();
break;
case 4:
break;
default:
Console.WriteLine("Invalid option - Enter your option again: ");
goto WrongMenu;
}
}
// All code for playing Lotto:
static void PlayMenu()
{
Console.Clear();
Console.WriteLine("=== PLAY MENU ===");
Console.WriteLine(" 1. Buy Tickets");
Console.WriteLine(" 2. Check Tickets");
Console.WriteLine(" 3. Back to Main Menu");
WrongPlayMenu:
Console.Write("\nEnter your option to continue: ");
playoption = Convert.ToInt32(Console.ReadLine());
switch (playoption)
{
case 1:
Console.Clear();
Console.WriteLine("=== PRIZES ===");
Console.WriteLine(" Lottery ticket = " + gameCost + " Euro");
Console.WriteLine(" Super Number Addon = " + superNumCost + " Euro");
Console.Write("\nHow many lottery tickets do you want to buy?: ");
gameAmount = Convert.ToInt32(Console.ReadLine());
if ((gameCost * gameAmount) <= cash)
{
cash = cash - (gameCost * gameAmount);
Console.WriteLine("Successfully bought " + gameAmount + " lottery tickets!");
if (cash - (gameAmount * superNumCost) >= 0)
{
Console.Write("\nDo you want to buy the Super Number Addon to maximize your potencial winnings? (Y/N): ");
includeSuperNum = Console.ReadLine();
while (includeSuperNum != "Y" && includeSuperNum != "N")
{
Console.WriteLine("Invalid answer - Type in your answer again only using Y for Yes or N for No.");
Console.Write("\nDo you want to buy the Super Number Addon to maximize your potencial winnings? (Y/N): ");
includeSuperNum = Console.ReadLine();
}
if (includeSuperNum == "Y")
{
cash = cash - (gameAmount * superNumCost);
superNumTickets += gameAmount;
Console.WriteLine("Successfully bought Super Number Addon for your ticket/s!");
}
else
{
tickets = tickets + gameAmount;
Console.WriteLine("No Super Number Tickets bought - Transaction done");
}
}
}
Console.WriteLine("\nPress any key to go back to Play Menu");
Console.ReadKey();
PlayMenu();
break;
case 2:
Console.Clear();
if (tickets == 0 && superNumTickets == 0)
{
Console.WriteLine("You have no tickets - Go buy some!");
Console.WriteLine("Press any key to go back to Play Menu");
Console.ReadKey();
PlayMenu();
}
if (tickets >= 1)
{
Console.WriteLine("\nYou have " + tickets + " normal tickets");
}
if (superNumTickets >= 1)
{
Console.WriteLine("You have " + superNumTickets + " tickets with the Super Number Addon.\n");
}
Console.WriteLine("=== BETTING ON TICKETS ===");
Console.WriteLine(" 1. Bet on normal tickets");
Console.WriteLine(" 2. Bet on Super Number tickets");
Console.WriteLine(" 3. Back to Play Menu");
BetWrong:
Console.Write("\nEnter your option by typing out the number: ");
betoption = Convert.ToInt32(Console.ReadLine());
switch (betoption)
{
case 1:
Bet();
break;
case 2:
SuperBet();
break;
case 3:
PlayMenu();
break;
default:
Console.WriteLine("Invalid answer - Try typing it again.");
goto BetWrong;
}
break;
case 3:
Main();
break;
default:
Console.WriteLine("Invalid answer - Try typing it again.");
goto WrongPlayMenu;
}
}
static void Bet()
{
Console.WriteLine("Your tickets:\n");
for (int x = 1; x <= tickets; x++)
{
Console.WriteLine(" Normal ticket Nr. " + x);
}
Console.Write("\nEnter the ticket number to bet on it: ");
int ticketNum = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nSuccessfully opened ticket Nr. " + ticketNum);
WrongRandomOption:
Console.Write("Do you want to randomize your 6 Numbers or write them out? Enter 1 for random or 2 for manual: ");
int chooseIfRandom = Convert.ToInt32(Console.ReadLine());
Random rnd = new Random();
switch (chooseIfRandom)
{
case 1:
Console.WriteLine("\nRandomized 6 numbers: ");
for (int z = 0; z <= 5; z++)
{
int rndNum = rnd.Next(1, 50);
randomList[z] = rndNum;
Console.Write(rndNum + ", ");
}
Console.WriteLine("\nThe correct Numbers are: ");
for (int c = 1; c <= 5; c++)
{
int correctNum = rnd.Next(1, 50);
correctList[c] = correctNum;
Console.Write(correctNum + ", ");
}
for (int h = 0; h <= 6; h++)
{
if (randomList[h] == correctList[h])
{
userCorrect++;
}
}
Console.WriteLine("You got " + userCorrect + " correct Numbers");
switch (userCorrect)
{
case 1:
Console.WriteLine("You won 3 Euros!");
cash += 3;
break;
case 2:
Console.WriteLine("Nice! You won 7 Euros!");
cash += 7;
break;
case 3:
Console.WriteLine("Wow! You won 12 Euros!");
cash += 12;
break;
case 4:
Console.WriteLine("Amazing! You won 50 Euros!");
cash += 50;
break;
case 5:
Console.WriteLine("Incredible! You won 4.200 Euros!");
cash += 4200;
break;
case 6:
Console.WriteLine("JACKPOT! You won 830.000 Euros!");
cash += 830000;
break;
}
userCorrect = 0;
break;
case 2:
for (int m = 0; m <= 6; m++)
{
ManualWrong:
Console.WriteLine("Enter your " + (m + 1) + ". number: ");
manualList[m] = Convert.ToInt32(Console.ReadLine());
if (manualList[m] >= 50 || manualList[m] < 1)
{
Console.WriteLine("Entered number is either too high or low - Enter again (Between 1 and 49)\n");
goto ManualWrong;
}
}
Console.WriteLine("\nYour numbers are: ");
for (int k = 0; k <= 6; k++)
{
Console.Write(manualList[k] + ", ");
}
Console.WriteLine("\nThe correct Numbers are: ");
for (int l = 1; l <= 6; l++)
{
int correctNum = rnd.Next(1, 50);
correctList[l] = correctNum;
Console.Write(correctNum + ", ");
}
for (int m = 0; m <= 6; m++)
{
if (manualList[m] == correctList[m])
{
userCorrect++;
}
}
Console.WriteLine("You got " + userCorrect + " correct Numbers");
switch (userCorrect)
{
case 1:
Console.WriteLine("You won 3 Euros!");
cash += 3;
break;
case 2:
Console.WriteLine("Nice! You won 7 Euros!");
cash += 7;
break;
case 3:
Console.WriteLine("Wow! You won 12 Euros!");
cash += 12;
break;
case 4:
Console.WriteLine("Amazing! You won 50 Euros!");
cash += 50;
break;
case 5:
Console.WriteLine("Incredible! You won 4.200 Euros!");
cash += 4200;
break;
case 6:
Console.WriteLine("JACKPOT! You won 830.000 Euros!");
cash += 830000;
break;
}
break;
default:
Console.WriteLine("Invalid answer - Only answer 1 or 2!");
goto WrongRandomOption;
}
Console.WriteLine("Press any key to go back to Play Menu.");
Console.ReadKey();
PlayMenu();
}
static void SuperBet()
{
Console.WriteLine("Your Super Number tickets:\n");
for (int y = 1; y <= superNumTickets; y++)
{
Console.WriteLine(" Super Number ticket Nr. " + y);
}
Console.Write("\nEnter the ticket number to bet on it: ");
int superTicketNum = Convert.ToInt32(Console.ReadLine());
}
// The Bank Menu
static void Bank()
{
Console.Clear();
Console.WriteLine("=== BANK MENU ===");
Console.WriteLine(" 1. Check balance");
Console.WriteLine(" 2. Deposit");
Console.WriteLine(" 3. Withdraw");
Console.WriteLine(" 4. Invest (Coming Soon)");
Console.WriteLine(" 5. Back to Main Menu");
WrongBankMenu:
Console.Write("\nEnter your option by typing out the number: ");
bankoption = Convert.ToInt32(Console.ReadLine());
switch (bankoption)
{
case 1:
Console.WriteLine("\nYour current bank balance is: " + balance + " Euros.");
Console.WriteLine("Your current balance of cash is: " + cash + " Euros.");
Console.WriteLine("\nPress any key to go back to Bank Menu.");
Console.ReadKey();
Bank();
break;
case 2:
NotEnoughCash:
Console.Write("Deposit amount: ");
deposit = Convert.ToInt32(Console.ReadLine());
if (deposit <= cash)
{
balance += deposit;
cash -= deposit;
Console.WriteLine("Successfully deposited " + deposit + " Euros!");
}
else
{
Console.WriteLine("You dont have enough to deposit this amount.");
Console.WriteLine("Your current maximum deposit amount is: " + cash + " Euros.\n");
goto NotEnoughCash;
}
Console.WriteLine("Press any key to go back to Bank Menu.");
Console.ReadKey();
Bank();
break;
case 3:
NotEnoughBalance:
Console.Write("Withdraw amount: ");
withdrawal = Convert.ToInt32(Console.ReadLine());
if (withdrawal <= balance)
{
balance -= withdrawal;
cash += withdrawal;
Console.WriteLine("Successfully withdrawn " + withdrawal + " Euros.");
}
else
{
Console.WriteLine("Your balance is smaller than your withdraw amount!");
Console.WriteLine("Your current maximum withdraw amount is: " + balance + " Euros.\n");
goto NotEnoughBalance;
}
Console.WriteLine("Press any key to go back to Bank Menu.");
Console.ReadKey();
Bank();
break;
case 4:
Console.WriteLine("This feature is coming soon!\n");
Console.WriteLine("Press any key to go back to Bank Menu.");
Console.ReadKey();
Bank();
break;
case 5:
Main();
break;
default:
Console.WriteLine("Invalid option - Enter your option again: ");
goto WrongBankMenu;
}
}
// All Code for working:
static void Work()
{
}
}
}

How do you properly use a Console.Readline() in a loop with string integer? [duplicate]

This question already has answers here:
How to replace multiple if statements i to more compact code/class in C#?
(5 answers)
Closed last year.
I'm baby-new to c# and building a project on mental health with multiple objects - starting with loops. Is there more tactful way to approach this code?
I ran basic code input via following:
Console.WriteLine("How are you feeling (1-bad to 5 great)?");
var userInput = Console.ReadLine();
Console.WriteLine(" Mood: " + userInput);
if (! Int32.TryParse(userInput, out x))
{
Console.WriteLine("Invalid data input");
}
else if (x == 1)
{
Console.WriteLine(" very low.");
}
else if (x == 2)
{
Console.WriteLine(" low.");
}
else if (x == 3)
{
Console.WriteLine(" average.");
}
else if (x == 4)
{
Console.WriteLine(" good.");
}
else if (x == 5)
{
Console.WriteLine(" very good.");
}
try this, it is more compact code
var invalidData = false;
var x = 0;
var moods = new string[] { " very low.", " low.", " average.", " good.", " very good." };
do
{
Console.WriteLine("How are you feeling(1 - bad to 5 great)?");
var userInput = Console.ReadLine();
Console.WriteLine(" Mood: " + userInput);
if (!Int32.TryParse(userInput, out x) || x < 1 || x > 5)
{
Console.WriteLine("Invalid data input");
invalidData = true;
}
else invalidData = false;
}
while (invalidData);
Console.WriteLine(moods[x-1]);

Minigame blackjack

For 2 players in a console app the game draws numbers from 1 to 10 instead of cards. With a do-while loop asking the question, whether you want to choose a card. I have a problem with giving the right word after the answer not, because then the loop should be broken and when it gives break it asks still and how to return it exits the program at the end the program says who won.
`enter code here` Console.WriteLine("now the first player's turn");
int number = 0;
Random r = new Random();
` do
{
Console.WriteLine("Are you downloading the card?");
string odp = Console.ReadLine();
switch (odp)
{
case "yes":
int rInt = r.Next(1, 10);
number += rInt;
Console.WriteLine(number);
break;
case "not":
?
}
if (number >= 22)
{
Console.WriteLine("The player 1 lost with {0} pkt", number);
break;
}
} while (number < 22);
Here is a version that seems to do what you need with your current code.
I add a boolean condition (bool continuePlaying) to stay inside the "do loop" or not.
using System;
namespace BlackJack
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("First player's turn");
int number = 0;
Random random = new Random();
bool continuePlaying = true;
do
{
Console.WriteLine("Are you downloading the card? [Y]es/[N]o");
string userAnswer = Console.ReadLine();
switch (userAnswer.ToLower())
{
case "y":
int randomNumber = random.Next(1, 10);
number += randomNumber;
Console.WriteLine($"Your total of points is: {number}");
continuePlaying = true;
break;
case "n":
Console.WriteLine($"Your total of points is: {number}");
continuePlaying = false; // Stop playing
break;
default:
Console.Clear();
Console.WriteLine("Please choose [Y]es or [N]o");
continuePlaying = true;
break;
}
} while (number < 22 && continuePlaying == true);
if (number <= 21)
{
Console.WriteLine($"You end the game with a total of {number} points");
}
else
{
Console.WriteLine($"The player 1 lost with {number} points");
}
Console.ReadLine();
}
}
}

Adding switch case

I want to add switch case to not allow the user to write string when entering temperature or when there is nothing to delete it says "there is nothing to delete, go back to menu".
List<string> Temp = new List<string>();
while (true)
{
string val;
Console.WriteLine("[L] ägg till temp-mätning: ");
Console.WriteLine("[S] kriv ut alla temperaturer och medeltemperatur");
Console.WriteLine("[T] ag bort temp-mätning");
Console.WriteLine("[A] vsluta");
Console.Write("Selection: ");
val = Console.ReadLine();
if (val == "l" || val == "L")
{
Console.WriteLine("add temperature : ");
Temp.Add(Console.ReadLine());
Console.Clear();
}
else if(val == "s" || val == "S")
{
int index = 1;
Console.Clear();
Console.WriteLine($"Your temperatures are: ");
Temp.ForEach(x => Console.WriteLine($"{index++} - {x}"));
}
else if (val == "t" || val == "T")
{
Console.Write($"Which temp do you want to delete [index from 1 to {Temp.Count}]: ");
int deleteIndex = int.Parse(Console.ReadLine()) - 1;
Temp.RemoveAt(deleteIndex);
}
else
{
Console.WriteLine("incorrect input: ");
Console.Clear();
break;
}
To control use input you can extract methods, e.g.
private static int ReadInteger(string title) {
while (true) {
if (!string.IsNullOrWhiteSpace(title))
Console.WriteLine(title);
if (int.TryParse(Console.ReadLine(), out int result))
return result;
Console.WriteLine("Incorrect syntax, please, try again.");
}
}
then you can put
val = Console
.ReadLine()
.Trim() // Let's be nice and tolerate leading / trailing spaces, e.g. " L "
.ToUpper();
val = val.Substring(0, Math.Max(1, val.Length));
switch (val) {
case "L":
// We read valid integer, turn it to string and out to Temp
Temp.Add(ReadInteger("add temperature : ").ToString());
Console.Clear();
break;
case "T":
int deleteIndex = ReadInteger(
"$"Which temp do you want to delete [index from 1 to {Temp.Count}]: ");
if (deleteIndex >= 0 && deleteIndex < Temp.Count)
Temp.RemoveAt(deleteIndex);
else
Console.WriteLine("Index out of range");
break;
...
}
Please check C# reference websites or books before asking questions.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/
Here is the code you wanted, hope this helps you:
List<string> Temp = new List<string>();
while (true)
{
menu:
string val = string.Empty;
Console.WriteLine("[L] ägg till temp-mätning: ");
Console.WriteLine("[S] kriv ut alla temperaturer och medeltemperatur");
Console.WriteLine("[T] ag bort temp-mätning");
Console.WriteLine("[A] vsluta");
Console.Write("Selection: ");
val = Console.ReadLine();
switch (val.ToLower())
{
case "l":
addTemperature:
Console.WriteLine("add temperature : ");
string temperatureInput = Console.ReadLine();
int temperatureToAddToList;
try
{
temperatureToAddToList = Convert.ToInt32(temperatureInput); //This line trys to convert string variables to integer variables. If string variable includes any character, it will throw an exception.
}
catch (Exception error) //If an exception was thrown, this code block gets activated, which will give out the message you asked for.
{
Console.Clear();
Console.WriteLine("Please enter a number instead of a string!");
goto addTemperature;
}
Temp.Add(temperatureInput.Trim());
Console.Clear();
break;
case "s":
int index = 1;
Console.Clear();
Console.WriteLine($"Your temperatures are: ");
Temp.ForEach(x => Console.WriteLine($"{index++} - {x}"));
break;
case "t":
if (Temp.Count == 0)
{
Console.Clear();
Console.WriteLine("There is nothing to delete, go back to menu.");
goto menu;
}
else
{
Console.Write($"Which temp do you want to delete [index from 1 to {Temp.Count}]: ");
int deleteIndex = int.Parse(Console.ReadLine()) - 1;
Temp.RemoveAt(deleteIndex);
break;
}
default:
Console.WriteLine("incorrect input: ");
Console.Clear();
break;
}
I have revised and updated my code example to better solve your problem.

Error when trying to do math equation

I am new to Console Application, I usually use C# for Unity. The code doesn't really work how I want it
Yes I know using Goto isn't good. But I don't know alternatives
I had [ a = 2 ] [ b = 3 ] and [ ans = a+b ] so the obvious answer is 5. So when you put 5 it runs the Else statement which is getting it incorrect.
goto start;
error:
Console.Clear();
Console.WriteLine("Input not Recognized");
Console.WriteLine("Try Again");
Console.WriteLine("\nType (Reset) to Reset Program");
Console.WriteLine("\nType (End) to End Program");
Console.WriteLine("");
string error1 = Console.ReadLine();
if (error1.Equals("reset", StringComparison.InvariantCultureIgnoreCase))
{
goto start;
}
if (error1.Equals("end", StringComparison.InvariantCultureIgnoreCase))
{
Environment.Exit(0);
}
else
{
goto error;
}
start:
Console.WriteLine("Solve the Math Equation");
int a = 2;
int b = 3;
int ans = a + b;
Console.WriteLine("\n2 + 3");
Console.WriteLine("");
string user = "";
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace)
{
double val = 0;
bool _x = double.TryParse(key.KeyChar.ToString(), out val);
if (_x)
{
user += key.KeyChar;
Console.Write(key.KeyChar);
}
}
else
{
if (key.Key == ConsoleKey.Backspace && user.Length > 0)
{
user = user.Substring(0, (user.Length - 1));
Console.Write("\b \b");
}
}
}
while (key.Key != ConsoleKey.Enter);
if (user.Equals(ans))
{
Console.Clear();
Console.WriteLine("Correct!");
Console.WriteLine("\nYour answer " + ans);
Console.WriteLine("\nType (End) to End Program");
Console.WriteLine("");
string end1 = Console.ReadLine();
if (end1.Equals("end", StringComparison.InvariantCultureIgnoreCase))
{
Environment.Exit(0);
}
else
{
goto error;
}
}
else
{
Console.Clear();
Console.WriteLine("Incorrect!");
Console.WriteLine("\nThe answer was " + ans);
Console.WriteLine("\nType (Reset) to Reset Program");
Console.WriteLine("Type (End) to End Program");
Console.WriteLine("");
string rne1 = Console.ReadLine();
if (rne1.Equals("reset", StringComparison.InvariantCultureIgnoreCase))
{
Console.Clear();
goto start;
}
if (rne1.Equals("end", StringComparison.InvariantCultureIgnoreCase))
{
Environment.Exit(0);
}
else
goto error;
Your user and ans are not equal in your code which is why your code jumps to the error. The reason why they are not equal are their Types.
user is a string
ans is an integer
So you are comparing "5" to 5 and that can not be equal.
Convert one of the variables so you have the same type.
Either use user.Equals(ans.ToString()) in the if statement or convert the string to a number (which is the better solution IMO - because it also handles the situation when the input is not a number). Like this:
int userAns;
if (!Int32.TryParse(user, userAnsj))
Console.WriteLine("Input is not a valid integer.");
and then comapare userAns to ans.

Categories