Why does it keep looping at Would You Like To Try Again? - c#

Ok so I am trying to run this
static void Main(string[] args)
{
string ans;
bool Operation = false;
Console.WriteLine("Hello user, would you like to do maths today? Write yes or no.");
ans = Console.ReadLine();
ans.ToLower();
do
{
Console.WriteLine("Would you like to try again?");
string answerFinal = Console.ReadLine();
answerFinal.ToLower();
if (answerFinal == "yep")
{
Operation = true;
}
else
{
Operation = false;
}
}
while (Operation == true);
}
However, it keeps looping at Would You Like To Try Again if I keep pressing yes, any ideas why? I think it has to do with Try Catch, can someone tell me how to use them in this instance?

ans.ToLower();
doesn't modify anything in ans, it returns a copy of ans as lowercase. You need to do this:
ans = ans.ToLower();
For each time you use .ToLower(), like for answerFinal.

The problem is that you are using the same variable here
Console.WriteLine("Hello user, would you like to do maths today? Write yes or no.");
ans = Console.ReadLine();
ans.ToLower();
and here
Console.Clear();
Console.WriteLine("Please select from one of the operations!");
Console.WriteLine("Either write Multiplication, Division, Addition or Subtraction.");
ans = Console.ReadLine();
ans.ToLower();
So by the time the do-while starts again, the value in ans has already changed and isn't yes any longer so it just goes to the last statement. Change the second part of the code to
Console.Clear();
Console.WriteLine("Please select from one of the operations!");
Console.WriteLine("Either write Multiplication, Division, Addition or Subtraction.");
string answer = Console.ReadLine();
answer = answer.ToLower();
if (answer == "multiplication")
{
//other statements
Also, change
ans.ToLower();
to
ans = ans.ToLower();
and the same for the likes

You assign your ans variable to a bunch of different values in your loop, none of them being "yes". Then when you come back into the do loop again you fail the first condition statement if (ans == "yes"). This will be false, causing you to keep skipping over that block of code, landing you right back to the "Would you like to try again" line.

Related

I've created an infinite loop and I don't know why

namespace ChooseYourOwnAdventure
{
class Program
{
static void Main(string[] args)
{
/* THE MYSTERIOUS NOISE */
// Start by asking for the user's name:
Console.Write("What is your name?: ");
string name = Console.ReadLine();
Console.WriteLine($"Hello, {name}! Welcome to our story.");
Console.WriteLine("It begins on a cold rainy night. You're sitting in
your room and hear a noise coming from down the hall. Do you go
investigate?");
Console.WriteLine("Type YES or NO");
string noiseChoice = Console.ReadLine();
string answer = noiseChoice.ToUpper();
if(answer == "NO")
{
Console.WriteLine("Not much of an adventure if we don't leave our
room. THE END");
return;
}
else if (answer == "YES")
{
Console.WriteLine("You walk into the hallway and see a light coming
from under a door down the hall. You walk towards it. Do you open it
or knock?");
}
else
{
Console.WriteLine("Command not recognized");
while((answer != "YES") || (answer != "NO"))
{
Console.WriteLine("Type YES or NO");
}
}
Console.WriteLine("Type OPEN or KNOCK");
string doorChoice = Console.ReadLine();
string answer2 = doorChoice.ToUpper();
I'm doing an exercise in Codecademy. I was creating my own adventure story before I did this so I thought this would be great practice to do anything that came to mind. I decided to do some error handling checks in case a user puts in some information which is where the else code block came from. I figured that if I used the while statement for any current and future errors the user introduces I could use the Console.WriteLine method to put the question forth until they type the specified values. Instead, the while I've created seems to have made an infinite loop within the compiler of "Type YES or NO". Can someone help me understand where I went wrong?
Every string is either not equal to "YES" or not equal to "NO" (e.g., if the input is "YES", it will not be equal to "NO", so the loop will continue). Instead of || (the logical "or" operator), you should use && (the logical "and" operator):
while((answer != "YES") && (answer != "NO"))
{
Console.WriteLine("Type YES or NO");
}
You are not re-assigning the answer variable in the while() loop you have made. #Mureinik is correct with why the loop is always active, but if they enter an input other than YES or NO then it will be infinite again. Try adding something like this:
while((answer != YES) && (answer != NO))
{
Console.WriteLine("Type YES or NO");
noiseChoice = Console.ReadLine();
answer = noiseChoice.ToUpper();
}
Because you were never updating the answer variable the while() loop's statement was always true, hence the infinite loop.

How to loop trough dictionary and check if the ReadLine input is equal to the Dictionary Key

int userInput = Convert.ToInt32(Console.ReadLine());
foreach (KeyValuePair<int,Library> lib in dictionary)
{
if (userInput == lib.Key)
{
Console.WriteLine("You chose book = {0}",lib.Value.bookName);
}
else
{
Console.WriteLine("Wrong Input");
}
}
Hello i am stuck at figuring out how i can check equality userInput(ReadLine) to a Key in Dictionary without else command spamming "Wrong Input" while looping trough Dictionary.
Seems like there is a method ContainsKey in the .Net lib.
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.containskey?view=netframework-4.8
You can simply call this and removed the whole loop.
Similar to the Linq implementation by Nasar, you could use the TryGetValue method on dictionary (Docs).
The good thing about using TryGetValue is you only iterate the dictionary once to do 2 things.
Check if the value exists
Get the value from the dictionary
int userInput = Convert.ToInt32(Console.ReadLine());
if (dictionary.TryGetValue(userInput, out Library library))
Console.WriteLine($"You chose book = {library.bookName}");
else
Console.WriteLine("Wrong Input");
TryGetValue will return true if the record is found and false otherwise.
Try a boolean to verify
int userInput = Convert.ToInt32(Console.ReadLine());
bool exists= false;
foreach (KeyValuePair<int,Library> lib in dictionary)
{
if (userInput == lib.Key)
{
Console.WriteLine("You chose book = {0}",lib.Value.bookName);
exists = true;
}
}
if(!exists){
Console.WriteLine("Wrong Input");
}
Currently your code is essentially saying "for each key in the dictionary that is not equal to the one the user has entered then print wrong input.." which is clearly not what you want.
instead you want something along the lines of:
"iterate through the entire dictionary and if every single key is not equal to the one the user has entered then print wrong input..."
in order to achieve that:
you don't need an else block within the loop.
use a simple boolean variable that will tell you whether a match has been found or not during the iteration and then after the loop check the state of the boolean and then print "wrong input" if necessary.
Example:
bool wrongInput = true;
int userInput = Convert.ToInt32(Console.ReadLine());
foreach (KeyValuePair<int,Library> lib in dictionary)
{
if (userInput == lib.Key)
{
Console.WriteLine($"You chose book = {lib.Value.bookName}");
wrongInput = false;
break; // exit early as there's no need to continue the iterating.
}
}
if (wrongInput) Console.WriteLine("Wrong Input");
Note that I've corrected your code for completeness but I would not recommend following the above approach i.e. iterating over a dictionary, instead look into ContainsKey instead of looping over the dictionary.... as it's the idiomatic, less code, more readable etc...
You could utilize LinQ for this and shorten the code making it simple and easy to read. is would spend more time trying to validate the input from the user and make sure that the imputed value is a digit and nothing else.
int userInput = Convert.ToInt32(Console.ReadLine());
var result = dictionary.FirstOrDefault(x => x.Key == userInput);
if(result.Value != null)
Console.WriteLine("You chose book = {0}", result.Value);
else
Console.WriteLine("Wrong Input");
An alternative way would also to run a Boolean expression validating if the key exist before executing the fetch value.
int userInput = Convert.ToInt32(Console.ReadLine());
var result = dictionary.ContainsKey(userInput);
if(!result)
Console.WriteLine("Wrong Input");
else
{
var book = dictionary.FirstOrDefault(x => x.Key == userInput);
Console.WriteLine("You chose book = {0}", book.Value);
}

Why do I have to enter my response two times for it to register?

I'm making a hypotenuse calculator in C#, but when the function asking if you want to solve another equation runs, it doesn't proceed unless the response if given twice.
Here's the function that's giving me trouble.
void _Again()
{
Console.WriteLine("Would you like to go again? y/n");
string again = Console.ReadLine();
string ag = Console.ReadLine();
if (ag == "y")
{
Console.WriteLine("Going again.");
_Prompt();
}
if (ag == "n")
{
Console.WriteLine("Exiting.");
Environment.Exit(0);
}
else if (ag != "n" && ag != "y")
{
Console.WriteLine("You have not entered a valid response.");
_Again();
I want this to proceed to the next function after entering either 'y' or 'n' just once. I've gotten no error messages so I don't really know what's going on here.
Thanks for any help you can give.
Your code simply has two Console.ReadLine() statements, and the return value of the first is not used.
That is, change
Console.WriteLine("Would you like to go again? y/n");
string again = Console.ReadLine();
string ag = Console.ReadLine();
to
Console.WriteLine("Would you like to go again? y/n");
string ag = Console.ReadLine();
and you should be golden.

How do I inserting a loop in an while, if-else statement in C#?

I'm trying to complete a sort of homework I have, which is supposed to ask for a decimal-number. If writen with . instead of , the text "You need to write your decimal-number with an (,) following Swedish standard".
Here I want the program to loop back, so the user will have to retry until the decimal-number is entered with an (,).
After this the program shall ask how many decimals you want to round it down to. But currently my program just put out text that you need to use , according to Swedish standard FOLLOWED by text "how many decimals do you want to round it down to" without looping the first statement if wrong.
I have currently tried changing a few things but it often leads to that the program crashes. I currently uses "else break;" on to places and the code is not completed but functional. More code is needed to complete my task, but currently stuck on the loop-issue
static void Main(string[] args)
{
double value1;
int round1;
while (true)
{
Console.Write("Enter a decimal-number: ");
string StrValue = Console.ReadLine();
bool success = Double.TryParse(StrValue, out value1);
if (!success)
{
Console.WriteLine("You need to use (,) as decimal-sign according to Swedish standard!"); //From here I want a loop if . is used instead of ,
}
Console.Write("With how many decimal-numbers do you want to round it down to?: ");
string StrRound = Console.ReadLine();
bool success1 = Int32.TryParse(StrRound, out round1);
if (!success1)
{
Console.WriteLine("Only use whole numbers when rounding");
}
else break;
}
}
}
}
I expected the program to loop after first statement, but I cant figure out why it doesn't and how I should fix this!
Replace the if condition with a while loop, try this:
static void Main(string[] args)
{
double value1;
int round1;
while (true)
{
Console.Write("Enter a decimal-number: ");
string StrValue = Console.ReadLine();
bool success = Double.TryParse(StrValue, out value1);
while (!success)
{
Console.WriteLine("You need to use (,) as decimal-sign according to Swedish standard!"); //From here I want a loop if . is used instead of ,
StrValue = Console.ReadLine();
success = Double.TryParse(StrValue, out value1);
}
Console.Write("With how many decimal-numbers do you want to round it down to?: ");
string StrRound = Console.ReadLine();
bool success1 = Int32.TryParse(StrRound, out round1);
if (!success1)
{
Console.WriteLine("Only use whole numbers when rounding");
}
else break;
}
}
}

Console Application with C# Not Displaying WriteLine if Bool is True

I am just starting to learn C# as my first programming language, so I decided to make a simple question and answer C# console application. The console will ask you a question, and if you get it right it will say "Correct". After a while I got it all to work with no errors, except it never said "Correct"
using System;
namespace Project
{
class MainClass
{
public static void Main (string[] args)
{
byte answer = 0;
Console.WriteLine ("What is 27+4?");
Console.ReadLine ();
if (answer == 31)
{
bool answerCorrect = true;
if (answerCorrect == true)
Console.WriteLine ("Correct!");
}
}
}
}
Thanks for all your help!
Because Console.ReadLine() reads your input(as a string), but it's not assigned to your variable answer. To make your program work, change the line to:
answer = byte.Parse(Console.ReadLine());
But remember to improve your code, for example, using int instead of byte, and the code in if (answer == 31) block can be shorter, etc. Good luck.
You must store the string return value from ReadLine and parse that. Like so:
byte answer = 0;
Console.WriteLine("What is 27+4?");
string s = Console.ReadLine();
if (byte.TryParse(s, out answer) && answer == 31)
{
bool answerCorrect = true;
if (answerCorrect == true)
Console.WriteLine("Correct!");
}
Try this one.
using System;
namespace Project
{
class MainClass
{
public static void Main (string[] args)
{
byte answer = 0;
Console.WriteLine ("What is 27+4?");
answer = byte.Parse(Console.ReadLine ());
if (answer == 31)
{
bool answerCorrect = true;
if (answerCorrect == true)
Console.WriteLine ("Correct!");
}
}
}
}
Console.Readline() returns the string value entered by the user, so firstly capture that input.
string input = Console.ReadLine ();
Next check if the input is correct by using String.Equals method to compare
if(input.Equals("31"))
and lastly there's no need to create and assign a value to an answerCorrect variable since if the code goes into the if statement the answer is correct, so just Console.WriteLine ("Correct!") inside.
First I would use int instead of byte. Then you have to assign the userinput to your variable answer. The type int provides a method called .Parse(string s) which tries to convert the string you get from Console.ReadLine() to an int. Of course it fails if the input is something like "hello". That's a good thing to look at to improve later.
Your use of bool answerCorrect may be correct, but remember: the comparison always "returns" a bool, so you don't really need an extra one.
Lastly, you're missing one important line Console.Read(); at the very end in your main-method. It's a bit cheaty but your program then waits for a userinput and the console window stays open and you can actually see what's in there.
static void Main(string[] args)
{
int answer = 0;
Console.WriteLine("What is 27 + 4?");
answer = int.Parse(Console.ReadLine());
if (answer == 31)
{
Console.WriteLine("Correct!");
}
else //I added this part for beauty reasons
{
Console.WriteLine("Incorrect!");
}
Console.Read();
}
I recommend you to have a look at while to run your program as long as the user gives the wrong answer and try..catch to accept "hello" as an input but handle it differently, to improve even more.
Good job though for your first C# application.

Categories

Resources