Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 5 years ago.
Improve this question
I have a piece of code I'm working with, that involves checking a condition and moving backwards to re-enter information if an invalid input is made. Please find the code, below:
Gender:
Console.WriteLine("Select Gender"
+"\n (M)ale/(F)emale");
input = Console.ReadLine();
if (input=="M" || input==("m"))
commonobj.gender = 1;
else if (input != ("F")||input!="f")
{
Console.WriteLine("Invalid input, please enter again");
goto Gender;
}
Intended behaviour:
If the user inputs 'M' or 'm', the value of the object variable is changed.
If the user inputs 'F' or 'f', the value of the object variable is unchanged.
If the user inputs any other value, an error statement should be displayed and the user asked to re-enter the information.
Variables used:
input - local variable, type String
| commonobj.gender - object variable
Current behaviour:
Entering 'F' or 'f' on the console displays the code under the 'else if' loop,
What am I doing wrong?
Note: The code executes as intended with 'm' being selected on the input.
You need an and in your last conditional statement
Gender:
Console.WriteLine("Select Gender"
+"\n (M)ale/(F)emale");
input = Console.ReadLine();
if (input=="M" || input==("m")) {
commonobj.gender = 1;
} else if (input != ("F") && input!="f")
{
Console.WriteLine("Invalid input, please enter again");
goto Gender;
}
Better to use
if (input.Equals("M", StringComparison.CurrentCultureIgnoreCase)) {
commonobj.gender = 1;
} else if (!input.Equals("F", StringComparison.CurrentCultureIgnoreCase))
{
Console.WriteLine("Invalid input, please enter again");
goto Gender;
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 1 year ago.
Improve this question
Console.WriteLine("Would you like to go first or second?");
string firstSecond = Console.ReadLine().ToUpper();
if (firstSecond == "FIRST")
{
Console.WriteLine("1");
}
else if (firstSecond == "SECOND")
{
Console.WriteLine("2");
}
else
{
string input = "x";
bool first = input == "FIRST";
bool second = input == "SECOND";
do
{
Console.WriteLine("Please say first or second:");
input = Console.ReadLine().ToUpper();
}
while (!(first | second));
}
The do while loop keeps on going even if I type first or second, I tried changing how I state the boolean but nothing seems to work. I am new so I am might some silly mistakes. How do I fix this?
You must put first and second condition into do while loop.
string input;
bool first;
bool second;
do {
Console.WriteLine("Please say first or second:");
input = Console.ReadLine().ToUpper();
first = input == "FIRST";
second = input == "SECOND";
}
while (!(first || second));
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 2 years ago.
Improve this question
I was doing the project for methods on Codecademy and was having trouble saving a ReadLine input into a variable and use it in a switch case statement. I tried my best to look up the issue but couldn't figure it out myself. I'm an absolute beginner, so please forgive me if this is trivial or has been answered before.
The relevant section of my code looks as follows:
public static void CalculateTotalCost()
{
retry:
Console.Write("What monument would you like to have calculated? (Teotihuacan, Taj Mahal or Great Mosque): ");
input = Console.ReadLine();
switch(input)
{
case "Teotihuacan":
break;
case "Taj Mahal":
break;
case "Great Mosque":
break;
default:
Console.WriteLine("Wrong entry, try again.");
goto retry;
}
}
My best guess was to declare my variable 'input' as a string but weirdly enough codecademy would crash every time i tried saving my code that way.
Try changing the beginning of your method from:
public static void CalculateTotalCost()
{
retry:
to:
public static void CalculateTotalCost()
{
string input;
retry:
Also, please don't use goto.
There are much better ways.
Try using a loop:
string name = null;
while (name == null)
{
Console.WriteLine("Please enter meaningful information");
string input = Console.ReadLine();
switch (input)
{
case "Teotihuacan":
name = input;
break;
default:
break;
}
}
Console.WriteLine($"You selected: {name}");
You have not declared the input variable.
Do it by
string input;
And then use it.
Or
string input = Console.ReadLine();
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Everthing if fine with the code by now but there is a better method to avoid null inputs in Console.ReadLine, I already have tried if statement but the code end up looking like a mess.
class ColocarMoedas
{
public static void Colocar(MaquinaUsuario user)
{
int m1, m5, m10, m25, m50;
Console.Clear();
Console.WriteLine("/////////////////////////MOEDAS////////////////////////////");
Console.Write("1 Centavo: ");
m1 = int.Parse(Console.ReadLine());
Console.Write("5 Centavo: ");
m5 = int.Parse(Console.ReadLine());
Console.Write("10 Centavo: ");
m10 = int.Parse(Console.ReadLine());
Console.Write("25 Centavo: ");
m25 = int.Parse(Console.ReadLine());
Console.Write("50 Centavo: ");
m50 = int.Parse(Console.ReadLine());
user.Adicionar(m1, m5, m10, m25, m50);
Console.Clear();
}
}
There is a better way of avoiding null inputs in Console.ReadLine
instead of if statements
The answer is yes.
Though it's worth noting, there are more things that can go wrong with user input than just null. In fact null is pretty rare, it's everything else you need to worry about.
The most idiomatic way to validate user numeric input is with TryParse style methods, which return a bool when the value can't be parsed and returns a value through an out parameter when true.
Int32.TryParse Method
Converts the string representation of a number to its 32-bit signed
integer equivalent. A return value indicates whether the operation
succeeded.
You can take it a step further by using a validation loop
int m1 = 0;
while (!int.TryParse(Console.ReadLine(), out m1))
Console.WriteLine("You hard one job! Now try again");
Essentially the above says, while the number can't be converted to an integer, which includes typos, empty input, and Ctrl+c (null), write a message.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 5 years ago.
Improve this question
So this should be super simple , perhaps indexOf is not the way to go
var incoming = "MDd"; // incoming data
List<string> cities = new List<string>();
cities.Add("MD");
cities.Add("Mumbai");
cities.Add("Berlin");
cities.Add("Istanbul");
if(cities.IndexOf(incoming) != 1 )
{
Console.WriteLine("found");
}
else
{
Console.WriteLine("not found");
}
I am seeing "found" with linqpad output , whether it is correct "MD" or "MDd" why? and what do I change to fix this?
From the documentation of IndexOf:
Return Value The zero-based index position of value if that string is
found, or -1 if it is not. If value is String.Empty, the return value
is 0.
When value is not found in the string, it returns -1, otherwise it returns index position, which is greater than or equal to 0. So either check if index is not -1 or check if it >= 0. I personally prefer the latter one:
// if (cities.IndexOf(incoming) != -1)
if (cities.IndexOf(incoming) >= 0)
{
Console.WriteLine("found");
}
This is a typo error. You want to check for -1 rather than 1 in your if statement:
if(cities.IndexOf(incoming) != -1)
{
Console.WriteLine("found");
}
else
{
Console.WriteLine("not found");
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 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 simply very confused and could use some help. I dont really know what is going on with the return of num in numCheck method. My teacher said that it should look how it does now so what was returned and how can I use it? I am trying to make a program that asks for the answer to a math problem (e.g. 2 + 2) and if the users input is 4 it end but anything else it asks again. This should have taken 5 mins, I just dont understand what he meant. Thank you!
namespace readNumber
{
class Program
{
static void Main(string[] args)
{
//should be a loop around this method call
//for(......)
numCheck();
Console.ReadLine();
}
static int numCheck()
{
bool itWorked;
int num;
do
{
Console.Write("Enter a Number: ");
string numSt = Console.ReadLine();
Console.WriteLine(numSt);
itWorked = int.TryParse(numSt, out num);
if (itWorked)
{
Console.WriteLine("Integer assigned: " + num);
}
else
{
Console.WriteLine("It Failed");
}
}
while (!itWorked);
return num;
}
}
}
The error I get most is "the name "num" does not exist in the current context" whenever I try to use num in the main program
I will answer the question :
what was returned and how can I use it?
The returned value num of the method numCheck is simply the number entered by the user, actually the method keeps looping until the user enters a valid number, than it breaks the do-while loop and returns num.
Now, you can use checkNum as it is to acquire numbers from the user.
Example:
Console.WriteLine("What is 2+2 ?");
int ans = checkNum();
if(ans == 4)
{
Console.WriteLine("Yes ! that is correct");
}
else
{
Console.WriteLine("No!, false answer");
}
You have not defined any variable named num in your main.
In order to use the value returned from checkNum() you need to assign it to a variable like in the solution by #chouaib.
your main should be like this
static void Main(string[] args)
{
int num;
//should be a loop around this method call
//for(......)
num = numCheck();
Console.ReadLine();
}