Cant get While loop to work [closed] - c#

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I am using a while loop to make it where if the user types anything other than "Yes" or "No" it will tell them to type something new in but everytime they type something else in it just spams "That is not an option" instead of starting back from the top. Can someone explain to me why? Thank you in advance.
using System;
class CalculatorProgram
{
//varibale for do-while loop
private static string endAnswer;
public static void Main() // <----- The Entry point
{
//Variables
string Choice1;
string mathChoice;
decimal Num1;
decimal Num2;
decimal Answer;
bool userWrong = true;
Console.Write("Would you like to use Lane's Custom Calculator?(Yes/No): ");
Choice1 = Console.ReadLine();
while(userWrong)
{
if (Choice1 == "Yes")
{
do
{
Console.Write("Would you like to Add, Subtract, Multiply, or Divide? (Case Sensitive): ");
mathChoice = Console.ReadLine();
//User inputs the 2 numbers
//Math Choices
if (mathChoice == "Add")
{
Console.WriteLine("What 2 numbers would you like to use?");
Console.Write("Number 1 is: ");
Num1 = decimal.Parse(Console.ReadLine());
Console.Write("Number 2 is: ");
Num2 = decimal.Parse(Console.ReadLine());
Answer = Num1 + Num2;
Console.WriteLine("Your expression is: " + Num1 + " + " + Num2 + " = " + Answer);
}
else if (mathChoice == "Subtract")
{
Console.WriteLine("What 2 numbers would you like to use?");
Console.Write("Number 1 is: ");
Num1 = decimal.Parse(Console.ReadLine());
Console.Write("Number 2 is: ");
Num2 = decimal.Parse(Console.ReadLine());
Answer = Num1 - Num2;
Console.WriteLine("Your expression is: " + Num1 + " - " + Num2 + " = " + Answer);
}
else if (mathChoice == "Multiply")
{
Console.WriteLine("What 2 numbers would you like to use?");
Console.Write("Number 1 is: ");
Num1 = decimal.Parse(Console.ReadLine());
Console.Write("Number 2 is: ");
Num2 = decimal.Parse(Console.ReadLine());
Answer = Num1 * Num2;
Console.WriteLine("Your expression is: " + Num1 + " X " + Num2 + " = " + Answer);
}
else if (mathChoice == "Divide")
{
Console.WriteLine("What 2 numbers would you like to use?");
Console.Write("Number 1 is: ");
Num1 = decimal.Parse(Console.ReadLine());
Console.Write("Number 2 is: ");
Num2 = decimal.Parse(Console.ReadLine());
Answer = Num1 / Num2;
Console.WriteLine("Your expression is: " + Num1 + " / " + Num2 + " = " + Answer);
}
else
{
Console.WriteLine("This is not an option! Shutting Down..");
Console.ReadKey();
Environment.Exit(0);
}
//varibale for while loop to continue if selected Yes.
Console.Write("Another Equation?: ");
endAnswer = Console.ReadLine();
} while (endAnswer == "Yes");
//Goodbye Message
Console.WriteLine("Thank you for using my program, goodbye ");
Console.ReadKey();
Environment.Exit(0);
userWrong = false;
}
//If someone selects no for wanting to use my program.
else if (Choice1 == "No")
{
Console.WriteLine("Thank you for using my program, goodbye ");
Console.ReadKey();
Environment.Exit(0);
}
else
{
Console.WriteLine("That is not an option");
Console.ReadLine();
}
}
}
}

The program is waiting for the user to input a new answer after it prints out "That is not an option," you just never prompt them for it. You also never store Choice1 again based on their new input, so it will always check the first if condition in your do-while loop with whatever they initially put in.
To fix it, change your else branch body to something like this.
//...
else
{
Console.WriteLine("That is not an option");
// reprompt the user so they know to type something in
Console.Write("Would you like to use Lane's Custom Calculator?(Yes/No): ");
// store the new choice to recheck next loop iteration
Choice1 = Console.ReadLine();
}

Probably your problem is that you don’t make a correct validation of the input.
Now, you read the input from console and compare with a static string so
“Add” is different from “add” and different from “Add(space)“.
I suggest you to make a more strong input validation:
Console.Write("Would you like to Add, Subtract, Multiply, or Divide? (Case Sensitive): ");
mathChoice = Console.ReadLine();
mathChoice = mathChoice.ToUpper().Trim();
//User inputs the 2 numbers
//Math Choices
if (mathChoice == "ADD")
{
Console.WriteLine("What 2 numbers would you like to use?");
....
}

Related

DivideByZeroException not working and giving out random integers (such as 8) [duplicate]

This question already has answers here:
Why doesn't dividing by zero with doubles throw an exception?
(3 answers)
Closed 2 years ago.
{
**result4 = num1 / num2;**
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(name + " this is the final result of Divsion = " + result4);
Console.ReadKey();
Environment.Exit(0);
}
else if (op == "^")
{
result5 = Math.Pow(num1, num2);
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(name + " this is the final result of exponential calculations = " + result5);
Console.ReadKey();
Environment.Exit(0);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(name + " this operant does not match the listed operant...this terminal will be cleared and closed after any key is pressed");
Console.ReadKey();
Environment.Exit(0);
}
}
**catch(DivideByZeroException)**
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(name + " you can not divide by zero; math error");
}
This is part of the script...but this is the main part of the error. If need be I will post the full script. The two asterisks on top of the word result 4, and catch, is to indicate the two-piece of codes.
As far as I know double 0 can actually be something like 0,000000001. Meaning that is not dividing by zero, but dividing with a very small number, leading to close to infinity as a result, which you are getting.
In this very example you can simply test if your num2 is close enough to zero, and if so, throw an exception.
If(Math.Abs(num2) < 0,00001)
Throw DivideByZeroException

Stop program from crashing when pressing Enter

So, today I decided to start learning C# from scratch. I've managed to make a little math problems program. The thing is, whenever the user just presses enter without entering a value (or anything which isn't a number), the program crashes. I've read something about TryParse but I just can't get it.
Here's my code (part of it):
{
Random numberGenerator = new Random();
int num01 = numberGenerator.Next(1, 20);
int num02 = numberGenerator.Next(1, 20);
Console.WriteLine("Welcome, user.");
Console.ReadKey();
Fail2:
Console.WriteLine("¿What's " + num01 + "x" + num02 + "?");
int res1 = Convert.ToInt32(Console.ReadLine());
if (res1 == num01*num02)
{
Console.WriteLine("Your answer is correct");
Console.ReadKey();
}
else
{
goto Fail;
}
Thanks in advance!
Hello & welcome to StackOverflow! I have a couple of suggestions:
Avoid using goto
Replace all your Convert.X with X.TryParse whenever it's the user who gives you the value, since you don't know what it could be
Random numberGenerator = new Random();
int num01 = numberGenerator.Next(1, 20);
int num02 = numberGenerator.Next(1, 20);
Console.WriteLine("Welcome, user.");
Console.ReadKey();
// Always use a loop instead of goto statements!
while (true)
{
Console.WriteLine("¿What's " + num01 + "x" + num02 + "?");
// Old line: int res1 = Convert.ToInt32(Console.ReadLine());
// Problem: this assumes that Console.ReadLine() returns a valid number, e.g. "3"
// but as you said, the user can trick you and put something else
if (!int.TryParse(Console.ReadLine(), out int res1))
continue; // This will rerun the loop from the top, so the user will need to re-write a response
if (res1 == num01*num02)
{
Console.WriteLine("Your answer is correct");
Console.ReadKey();
}
else
{
break; // stop the outer loop on top
}
}
Use int.TryParse like this...
int res1 = 0;
if (!int.TryParse(Console.ReadLine(), out res1))
{
//failed;
}
if (res1 == num01*num02)
...
https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=netcore-3.1

Somehow my value never equals 1, is there a reason for that?

I can't ever get guessLimit to equal 1, in the system log when I enter the limit of guesses as 5 and start guessing, the guessLimit will go down all the way to 2 and it will give me the "You Lose" message without letting me do my final guess... is there a reason for that?
public static void Main(string[] args){
string guess = "";
bool outOfguesses = false;
int guessCount = 0;
Console.Clear();
Console.Write("Enter the amount of guesses you want: ");
int guessLimit = Convert.ToInt32(Console.ReadLine());
Console.Clear();
Console.Write("Enter a word that will be guessed...: ");
string secretWord = Console.ReadLine();
Console.Clear();
Console.Write("You have " + guessLimit + " guesses" + "\nEnter a guess: ");
guess = Console.ReadLine();
while(guess.ToLower() != secretWord.ToLower() && !outOfguesses){
if(guessLimit >= guessCount || guessLimit == 1){
guessCount++;
guessLimit--;
Console.Write("\nWRONG! You have " + guessLimit + " guesses left." + "\nEnter another guess: ");
guess = Console.ReadLine();
} else{
outOfguesses = true;
}
}
if(outOfguesses == true){
Console.WriteLine("\nSorry...\nYou lose!");
} else{
Console.WriteLine("\nGood Job.\nYou Win!!");
}
Console.ReadLine();
}
When your if statement reaches
(Is 2 >= 3) this is false so it will skip over the if and go to the else
Which is why it stops there.
Also change your guesslimit ==1 to <1

Guessing Game Number Issue

Before I get down-voted for the extensive code, I feel it's necessary for a solution to present itself.
I've made alterations to the program's code from the help previously presented, but I still seem to be falling into the problem that the random number number is either not being properly compared (I've had examples where number is '5' and the user's guess is '5', but I'm still getting a comment that "You're quite far off! Try again." meaning it's falling into else if (userinputcalc > 4 | userinputcalc < 10)...
So, at this stage the issue seems to lie within the comparison of number and the userinput, leading to confusing output messages.
I'm probably missing something obvious here, despite being sure it's around the loop of comparing number and userinput but I've been looking at this code and seeing nothing.
Any help is greatly appreciated, as always.
public void GuessingGame()
{
string username; // Will be the user's chosen name for program interaction
int guessesleft = 0;// Stands for the number of guesses left (out of 3)
int spaceaway = 0; // Space from the guess and the random number, if not correct guess
int roundcount = 1; //Started at 1 for the sake of the user interface - aesthetics
int number = 0; // Current value of the random number
int userinput = 0; //User input is the guess the user makes during the guessing game
int userinputcalc = 0;// calculation of guess and random number, when added to spaceaway calculation
int answersright = 0; // Number of times the user guessed the number correctly
Random rndm = new Random(); // Initialises a new class of random, which'll be used to simulate the random number
Console.WriteLine("Welcome to Guessing Game!");
Console.WriteLine("");
Console.WriteLine("Please press any button to continue.");
Console.ReadLine();
Console.WriteLine("What's your name?");
username = (Console.ReadLine());
//If you're wondering at all, the "You must guess what it is inthree tries." is intentional, since it was showing double-spaced in the command prompt
Console.WriteLine("Well, " + username + ", I am thinking of a number from 1 to 10. You must guess what it is inthree tries.");
Console.WriteLine("");
{
do
{
Console.WriteLine("Round" + roundcount); //Displays the which round (out of 10) to the user
guessesleft = 3; //The remaining guesses left for the user
do
{
number = rndm.Next(10) + 1; // int number is set to a random number between 1 and 10
Console.WriteLine("Please enter a guess:");
userinput = int.Parse(Console.ReadLine());
guessesleft = guessesleft - 1;
if (userinput == number)
{
//Below, once you've guessed right, you will have this message displayed in the console
Console.WriteLine("You guessed " + number + " *RIGHT*!");
answersright = answersright + 1;
guessesleft = 0;// No point need to guess further on something you've guessed correctly - saves correct answer value exploit
}
else if (userinput < 1 || userinput > 10) // If user's guess is less than 1 or more than 10, then out of range. Counts as a guess.
{
Console.WriteLine("You guessed " + userinput + "! and it was incorrect!");
Console.WriteLine("This is outside of the range of numbers between 1-10 ");
}
else if (userinput != number) // while the user's guess does not equal the number
{
{
// userinputcalc = Math.Abs(number - userinput);
//Left out as I was getting abnormal run-time outputs and the math showed up wrong.
//(Example: RND No. = 5 Userinput = 5 Output: "Incorrect" "Hot")
spaceaway = (number - userinput); // Works out how far from the random no. the user's guess is.
// If user guesses 6 and random no. is 5, answer will be -1 this makes the value +ve and allows output to be shown without error
if (spaceaway < 0)
{
spaceaway = (spaceaway * -1);
userinputcalc = spaceaway;
}
else if (spaceaway > 0)
{
userinputcalc = spaceaway;
}
}
{
if (userinputcalc < 2)
{
Console.WriteLine("You guessed " + userinput + "! and it was wrong!");
Console.WriteLine("Hot");
}
else if
(userinputcalc < 3)
{
Console.WriteLine("You guessed " + userinput + "! and it was wrong!");
Console.WriteLine("Warm");
}
else if
(userinputcalc < 4)
{
Console.WriteLine("You guessed " + userinput + "! and it was wrong!");
Console.WriteLine("Cold");
}
else if (userinputcalc > 4 | userinputcalc < 10)
{
Console.WriteLine("You guessed " + userinput + "! and it was wrong!");
Console.WriteLine("You're quite far off! Try again.");
}
}
}
} while (guessesleft > 0);
Console.WriteLine("");
Console.WriteLine("The number was, "+number+"!");
Console.WriteLine("");
roundcount = roundcount + 1;
} while (roundcount < 11);
Console.WriteLine("Well, " + username + ". " + "You guessed correctly, " + answersright + " times!");
}
}
}
}
OK I think theres quite a few issues here (some are off topic but definitely worth mentioning)..
I wouldn't advise using while loops to check for specific inputs
For example:
Instead of roundCount != 11 use roundCount < 11
Then there is less chance of forever getting stuck in a loop
You should declare Random outside of your loops otherwise you run the risk of just getting the same numbers ("randomly")
You reset the number to a new number after every guess so the user doesn't have a chance to guess the right number
With all this being said, I think the Math.Abs was correct if you are trying to find the distance away from the number.. I wouldnt use less than two though as that would mean only numbers that are 1 away from the answer are "hot"
Note: Answer is based off question revision #5
Update
Doesn't seem like you were far off but you still reset the number every loop
number = rndm.Next(10) + 1; //Insert here
do
{
//Displays the which round (out of 10) to the user
Console.WriteLine("Round" + roundcount);
guessesleft = 3; //The remaining guesses left for the user
do
{
// Remove this -- number = rndm.Next(10) + 1;
I think this is what you want,please try it:
static int guessesleft;
static Random ran = new Random();
static int MagicNumber;
static string UserInput;
static void Main(string[] args)
{
ConsoleKeyInfo ci = new ConsoleKeyInfo();
do
{
guessesleft = 3;
UserInput = "";
Console.Clear();
string username;
int guesscount = 1;
Console.WriteLine("Welcome to Jackie's Guessing Game!");
Console.WriteLine("");
Console.WriteLine("Please press any button to continue.");
Console.ReadLine();
Console.WriteLine("What's your name?");
username = (Console.ReadLine());
//If you're wondering at all, the "You must guess what it is inthree tries." is intentional, since it was showing double-spaced in the command prompt
Console.WriteLine("Well, " + username + ", I am thinking of a number from 1 to 10. You must guess what it is inthree tries.");
Console.WriteLine("");
MagicNumber = ran.Next(1, 11);
do
{
Console.WriteLine("Please insert your " + guesscount++ + "º guess!");
UserInput = Console.ReadLine().Trim();
if (UserInput == MagicNumber.ToString())
break;
if (Math.Abs(Convert.ToInt32(UserInput) - MagicNumber) < 2)
Console.WriteLine("Hot!!");
else if(Math.Abs(Convert.ToInt32(UserInput) - MagicNumber) < 3)
Console.WriteLine("Warm!!");
Console.WriteLine("No luck , you have " + --guessesleft + "º guesses left!");
Console.WriteLine();
} while (guesscount < 4);
if (guesscount == 4)
Console.WriteLine("Sorry " + username + " no more tries,you lost!");
else
Console.WriteLine("Congratulations your guess with number " + UserInput + " is correct,the number was " + MagicNumber);
Console.WriteLine("Press Q to quit or Enter to Play again!");
ci = Console.ReadKey();
} while (ci.Key != ConsoleKey.Q);
}

C# program does not evaluate operations and return wrong answers

Community.
I am learning how to program in C#. I wrote this small program that gets the name, age, favorite color, and two numbers from the user. I use Notepad ++ to write the code and run the C# compiler from the windows command prompt. Here is the source code of the program
using System;
class ShowSomething
{
static void Main(string[] args)
{
string name, age, favColor;
int num1,num2, sum, mult, subs;
float div;
Console.Write("What is your name? ");
name = Console.ReadLine();
Console.WriteLine("Hello, " + name);
Console.WriteLine();
Console.Write("How old are you? ");
age = Console.ReadLine();
Console.WriteLine("So you are " + age, "I thought that you were older!");
Console.WriteLine();
Console.Write("What is your favorite Color? ");
favColor = Console.ReadLine();
Console.WriteLine(favColor + " is a cool color!");
Console.WriteLine();
Console.WriteLine("Nice meeting you, " + name, "Have a good day!");
Console.WriteLine();
Console.WriteLine("Let us do some operations, " + name);
Console.WriteLine();
Console.Write("Please enter a number: ");
num1 = Console.Read();
Console.Write("Please enter another number: ");
num2 = Console.Read();
sum = num1 + num2;
mult = num1 * num2;
subs = num1 - num2;
div = num1 / num2;
Console.WriteLine();
Console.WriteLine("Alright, " + name, "Let us blow up your mind!");
Console.WriteLine();
Console.WriteLine(num1 + "+" + num2, "=" + sum);
Console.WriteLine(num1 + "*" + num2, "=" + mult);
Console.WriteLine(num1 + "-" + num2, "=" + subs);
Console.WriteLine(num1 + "/" + num2, "=" + div);
Console.WriteLine();
Console.WriteLine("Mindblown, Right?");
}
}
When I execute the program almost everything goes alright. However, when the user inputs the first number of the operations, the program skips the second prompt and print a completely different result from the one expected. For example, if I put 0 as the first number the program will jump to the operations and print the following:
//
48+13
48*13
48-13
48/13
Mindblown, right?
//
Do not use Console.Read as it does not do what is expected:
Reads the next character from the standard input stream (and returns the integer value1 that represents it).
Here a good explanation from devshort on why the second call to Console.Read "skips":
If you enter in the value "1" for the first thing, it'll convert that to the ascii representation. Then the carriage return is STILL in the screen [input] buffer, so when you hit the next read (Console.Read) it reads the newline and converts it to a number.
Instead, one approach is to use Console.ReadLine instead (which returns a string) in conjunction with int.Parse or similar ..
1 Hint: the carriage return character has a value of 13.
The ascii that is visually 0 has a byte value of 48. or 0x30. Which explains the 48.
Basically, you're using the wrong function.
Ok, I edited your code a little and added some explanation wy I changed somethings..
string name, age, favColor;
int num1, num2, sum, mult, subs;
float div;
Console.WriteLine("What is your name? ");
//Start a new line and write ..
name = Console.ReadLine();
//Read the whole line
Console.WriteLine("\nHello, {0}", name);
//{0} stands for the first variable you refer to after the, etc
Console.WriteLine("How old are you? ");
age = Console.ReadLine();
Console.WriteLine("\nSo you are {0}, I thought that you were older!", age);
// something new.. \n refers to a "new line", so instead of writing Console.Writeline(); you can use this
Console.WriteLine("What is your favorite Color? ");
favColor = Console.ReadLine();
Console.WriteLine("{0} is a cool color!\n", favColor);
Console.WriteLine("Nice meeting you, {0}", name);
Console.WriteLine("Have a good day!\n");
Console.WriteLine("Let us do some operations, {0}", name);
Console.WriteLine("Please enter a number: ");
num1 = Convert.ToInt16(Console.ReadLine());
//int.TryParse(Console.ReadLine(), out num1);
//Another way is to "try parse", try converting a string to an integer
Console.WriteLine("\nPlease enter another number: ");
num2 = Convert.ToInt16(Console.ReadLine());
//int.TryParse(Console.ReadLine(), out num2);
//Another way is to "try parse", try converting a string to an integer where out is the returning variable
sum = num1 + num2;
mult = num1 * num2;
subs = num1 - num2;
div = num1 / num2;
Console.WriteLine("\nAlright, {0}", name);
Console.WriteLine("Let us blow up your mind!\n");
//Again use {0} ... which writes easier than having to use + every time,
//its not wrong but its easier this way
Console.WriteLine("{0} + {1} = {2}", num1, num2, sum);
Console.WriteLine("{0} * {1} = {2}", num1, num2, mult);
Console.WriteLine("{0} - {1} = {2}", num1, num2, subs);
Console.WriteLine("{0} / {1} = {2}", num1, num2, div);
Console.WriteLine("\nMindblown, Right?");
Console.ReadLine();
//Console.ReadLine(); at the end to prevent the program from closing

Categories

Resources