Not entering if/else block [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 8 years ago.
Improve this question
I have the following code. When I type 0 into the console, I expect the console to display "Please re-enter your age" but that if block is never entered and the program exits. What am I doing wrong?
Console.WriteLine("Please entre your first name:");
Console.ReadLine();
Console.WriteLine("Please enter your last name:");
Console.ReadLine();
Console.WriteLine("Please type your age:");
Console.ReadLine();
int minAge = 18;
int maxAge = 68;
if (minAge < 18)
if (maxAge > 68)
Console.WriteLine("Please re-enter your age");
else
Console.WriteLine("Please choose f for female or m for male:");

You are not reading the user input into an age variable. When you do, you need to take account of the user possibly typing non-numeric characters. You're also not wrapping your if/else blocks inside curly braces which is resulting in the logical flow not matching your intentions.
The following code reads the console input into an age variable, rejecting unparseable input by using int.TryParse, and it retains your minAge and maxAge values as constants. We keep looping until the user has input a valid number as an age, and exit if they are ineligible to continue because they are too young or too old:
const int minAge = 18;
const int maxAge = 68;
int age;
do
{
Console.WriteLine("Please type your age:");
} while (!int.TryParse(Console.ReadLine(), out age));
if (age < minAge || age > maxAge)
{
Console.WriteLine("I'm sorry, this application is for people aged {0} to {1} only", minAge, maxAge);
return; // or exit console app
}
Console.WriteLine("Please choose f for female or m for male:");

You're not storing inputted age. Because of that the program never reach the next part, since you're comparing minAge with minAge and maxAge with maxAge. Maybe you can use
int age = Convert.ToInt32(Console.Readline())
edit : if you don't want any exception, you can handle it by using
int age;
bool res = Int32.TryParse(Console.Readline(), out age);
if (!res)
Console.WriteLine("Please re-enter your age");
then use them in the next part
if (age < minAge || age > maxAge )
Console.WriteLine("Please re-enter your age");
else
Console.WriteLine("Please choose f for female or m for male:");

try the following may be it helps,
int userage;
Console.WriteLine("Please type your age:");
userage=int.Parse(Console.ReadLine());
int minAge = 18;
int maxAge = 68;
if (userage>minAge || userage<maxAge)
Console.WriteLine("Age is not accepted");
else
Console.WriteLine("Your Age is {0}",userage.ToString());
//do what ever you want
//Console.WriteLine("Please choose f for female or m for male:");
Console.ReadLine();

Related

How to do while loop/Do while loop with sentinel value with switch

Hello I am trying to figure out why my program is not working, it's supposed to output a program in which department codes would be entered and followed by a prompt to enter a mark and so on until Q is entered. I can't seem to get that part working at all. If anyone could help please I will appreciate it.
// declare variables
char deptCode = ' ';
int count = 0;
double markVal, sum = 0, average = 0.0;
{
Console.WriteLine("Enter a department code: ‘C’ or ‘c’ for Computer Science,‘B’ or ‘b’ for History, ‘P’ or ‘p’ for Physics, or enter ‘Q’ or ‘q’ to quit:");
deptCode = Convert.ToChar(Console.ReadLine());
while (char.ToUpper(deptCode) != 'Q')
do
{
Console.Write("Enter a mark between 0 and 100 => ");
markVal = Convert.ToDouble(Console.ReadLine());
{
Console.WriteLine("Enter a department code: ‘C’ or ‘c’ for Computer Science,‘B’ or ‘b’ for History, ‘P’ or ‘p’ for Physics, or enter ‘Q’ or ‘q’ to quit:");
deptCode = Convert.ToChar(Console.ReadLine());
} while (markVal >= 0 && markVal <= 100);
count++;
average = (double)sum / count;
Console.WriteLine("***Error, Please Enter Valid Mark");
Console.WriteLine("The Average mark for Computer Science Students is {0}", average);
Console.WriteLine("The Average mark for Biology Students is {0}", average);
Console.WriteLine("The Average mark for Physics Students is {0}", average);
Console.ReadLine();
{
I am sympathetic to your dilemma and know it can be challenging to learn coding when you are not familiar with it. So hopefully the suggestions below may help to get you started at least down the right path. At the bottom of this is a basic “shell” but parts are missing and hopefully you will be able to fill in the missing parts.
One idea that you will find very helpful is if you break things down into pieces (methods) that will make things easier to follow and manage. In this particular case, you need to get a handle on the endless loops that you will be creating. From what I can see there would be three (3) possible endless loops that you will need to manage.
An endless loop that lets the user enter any number of discipline marks.
An endless loop when we ask the user which discipline to use
And an endless loop when we ask the user for a Mark between 0 and 100
When I say endless loop I mean that when we ask the user for a Discipline or a Mark… then, the user MUST press the “c”, “b” “p” or “q” character to exit the discipline loop. In addition the user MUST enter a valid double value between 0 and 100 to exit the Mark loop. The first endless loop will run allowing the user to enter multiple disciplines and marks and will not exit until the user presses the q character when selecting a discipline.
And finally when the user presses the ‘q’ character, then we can output the averages.
So to help… I will create two methods for you. One that will represent the endless loop for getting the Mark from the user… i.e.…. a number between 0 and 100. Then a second endless loop method that will get the Discipline from the user… i.e. … ‘c’, ‘b’, ‘p’ or ‘q’… and it may look something like…
private static char GetDisciplineFromUser() {
string userInput;
while (true) {
Console.WriteLine("Enter a department code: ‘C’ for Computer Science,‘B’ for Biology, ‘P’ for Physics, or enter ‘Q’ to quit:");
userInput = Console.ReadLine().ToLower();
if (userInput.Length > 0) {
if (userInput[0] == 'c' || userInput[0] == 'b' ||
userInput[0] == 'p' || userInput[0] == 'q') {
return userInput[0];
}
}
Console.WriteLine("Invalid discipline => " + userInput + " try again.");
}
}
Note… the loop will never end until the user selects the characters ‘c’, ‘b’, ‘p’ or ‘q’. We can guarantee that when we call the method above, ONLY those characters are returned.
Next is the endless loop to get the Mark from the user and may look something like…
private static double GetMarkFromUser() {
string userInput;
while (true) {
Console.WriteLine("Enter a mark between 0 and 100 => ");
userInput = Console.ReadLine().Trim();
if (double.TryParse(userInput, out double mark)) {
if (mark >= 0 && mark <= 100) {
return mark;
}
}
Console.WriteLine("Invalid Mark => " + userInput + " try again.");
}
}
Similar to the previous method, and one difference is we want to make sure that the user enters a valid number between 0 and 100. This is done using a TryParse method and most numeric types have a TryParse method and I highly recommend you get familiar with it when checking for valid numeric input.
These two methods should come in handy and simplify the main code. So your next issue which I will leave to you, is how are you going to store these values? When the user enters a CS 89 mark… how are you going to store this info? In this simple case… six variables may work like…
int totalsCSMarks = 0;
int totalsBiologyMarks = 0;
int totalsPhysicsMarks = 0;
double totalOfAllCSMarks = 0;
double totalOfAllBiologyMarks = 0;
double totalOfAllPhysicsMarks = 0;
Now you have something to store the users input in.
And finally the shell that would work using the methods above and you should see this uncomplicates things a bit in comparison to your current code. Hopefully you should be able to fill in the missing parts. Good Luck.
static void Main(string[] args) {
// you will need some kind of storage for each discipline.. see above...
char currentDiscipline = 'x';
double currentMark;
while (currentDiscipline != 'q') {
currentDiscipline = GetDisciplineFromUser();
if (currentDiscipline != 'q') {
currentMark = GetMarkFromUser();
switch (currentDiscipline) {
case 'c':
// add 1 to total number of CS marks
// add currentMarkValue to the total of CS marks
break;
case 'b':
// add 1 to total number of Biology marks
// add currentMarkValue to the total of Biology marks
break;
default: // <- we know for sure that only p could be left
// add 1 to total number of Physics marks
// add currentMarkValue to the total of Physics marks
break;
}
}
}
Console.WriteLine("Averages ------");
//Console.WriteLine("The Average mark for Computer Science Students is {0}", totalOfAllCSMarks / totalCSMarks);
//Console.WriteLine("The Average mark for Biology Students is {0}", ...);
//Console.WriteLine("The Average mark for Physics Students is {0}", ...);
Console.ReadLine();
}

Random Equation Test. Correct or Wrong answer

I have been trying to write a test which involves random numbers to make equations for the user to answer. I have wrote it so that two int are assigned to a random number and the console writes the equation. I have used an if statement for the program to dictate whether the users answer is correct or incorrect. However it is always either correct or incorrect depending on the code i write. I can't write it so that the program decides the answer.
int iE3 = rnd.Next(1, 11);
int iE13 = rnd.Next(1, 11);
int iA3 = iE3 * iE13;
int answer3 = iE3 * iE13;
Console.WriteLine("The third equation is {0} * {1}", iE3, iE13);
Console.ReadLine();
if ( answer3 == iA3)
{
Console.WriteLine("Well done you got it right!");
}
else
{
Console.WriteLine("Unfortunately you got it incorrect.");
}
You are ignoring the users input, you need to assign the result of the ReadLine:
int answer3 = Int32.Parse(Console.ReadLine());
Of course with error handling incase they don't enter a number etc...

Code won't give desired output or read second input

Sorry if this isn't the right. This is my first time posting here. I'm a first year Software student and for the life of me i cannot seem to get this to work. I know its something simple I'm missing but oh well. I tried doing this using methods but again no help. Maybe you guys could help me?
The problem is the code wont let me input after the "Are you a member (Y/N)" writline statement and just keeps giving me an output of 50.
static void Main(string[] args)
{
//Local Variable Declaration//
double rate1 = 10;
double rate2 = 3;
double maxCharge = 50;
double charge;
Console.WriteLine("Enter number of hours (-999 to quit) : ");
int hoursRented = Console.Read();
if (hoursRented >= 3)
{
charge = hoursRented * rate1;
}
else
{
charge = (3 * rate1) + (hoursRented * rate2);
}
if (charge > maxCharge)
{
charge = maxCharge;
}
Console.WriteLine("Are you a member? (Y/N) : ");
int memberStatus = Console.Read();
if (memberStatus.Equals("Y"))
{
charge = (charge * 1 / 10) - charge;
}
Console.WriteLine("Customer Charge : {0} Total Charge To Date : ", charge);
}
The problematic lines are below
Console.WriteLine("Enter number of hours (-999 to quit) : ");
int hoursRented = Console.Read();
if (hoursRented >= 3) {
and
Console.WriteLine("Are you a member? (Y/N) : ");
int memberStatus = Console.Read();
if (memberStatus.Equals("Y")) {
When you call Console.Read(), it reads only characters and returns it as an int. You seem to mistakenly think it will parse the character to an int.
Secondly, think what happens when you provide multiple characters as input to a single Console.Read() call. Interestingly, the remaining characters are read in the subsequent calls. So when you type any number followed by Enter in the first Console.Read it only, reads the first character, the subsequent characters, including the EOLN char are returned in the subsequent calls, instead of prompting you to enter information for the next call.
The fix is easy. Use Console.Readline() and int.parse (or its int.TryParse() variant
Then the corresponding code will look like below
Console.Write("Enter number of hours (-999 to quit) : ");
string hoursRentedStr = Console.ReadLine();
int hoursRented = int.Parse(hoursRentedStr);
if (hoursRented >= 3) {
and
Console.Write("Are you a member? (Y/N) : ");
string memberStatus = Console.ReadLine();
if (memberStatus.Equals("Y")) {
This is because you are just writing:
Console.WriteLine("Are you a member? (Y/N) : ");
and continuing through.
you must do it like this:
Console.WriteLine("Are you a member? (Y/N) : ");
Console.ReadLine();
and then:
int memberStatus = Int.Parse(Console.ReadKey());
your problem is that your are using Console.Read wich returns the ascii code of the next charachter as said by #juharr in the comments. so the solution is too simply replace Read By ReadLine and change your code like this, so that ReadLine wich is a string will be converted to the int value that you want
int hoursRented = int.Parse(Console.ReadLine());
And change your member status to a string to compare it with "Y" easily
string memberStatus = Console.ReadLine();
Note: if you want to validate the input you should use a int.TryParse instead of just a normal parse like I used as it returns a bool so you knows when it fails

Console Keypress not working?

So I'm making a console-based text game to learn more C# but I'm now stuck and have resorted to SO.
This might be an obvious answer but I require another pair of eyes to help me. I've checked the other questions on here and they don't seem to aid me.
In my Main(), I have the following:
int age;
Console.Write("Before entering the unknown, could you please confirm your age? ");
age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
if (age < 18)
{
Console.WriteLine("I'm sorry, you'll now be transferred to a non-explicit version.");
Console.WriteLine("\n<Press any key to continue>");
Console.ReadKey();
Console.Write("\nPlease wait...");
for (int t = 5; t >= 0; t--)
{
Console.CursorLeft = 22;
Console.Write("{0:00}" + " seconds remaining", t);
Thread.Sleep(1000);
}
Console.WriteLine("");
Console.WriteLine("\nTo proceed, please press any key...");
Console.ReadLine();
NonExplicit();
}
Self explanatory. Once it hits the NonExplicit() method, the following is called:
char yes = Console.ReadKey().KeyChar;
string name;
Console.WriteLine("\nYou're awake? It's about time. Not old enough, eh? That sucks. \n\nListen, I really need your help. Would you be interested? Y / N");
Console.ReadKey();
if (yes == 'y' || yes == 'Y')
{
Console.Write("\nYou will?! Wow, That's fantastic. Right then, where shall I start? \nI know! How about telling me your name? ");
name = Console.ReadKey().ToString();
Console.WriteLine("\nAhh yes, now you mention it, I certainly remember you, {0}!", name);
}
else
{
Console.WriteLine("\nYou don't want to help me? Oh, that's unfortunate... ");
}
What seems to happen is that, when 'y' or 'Y' is pressed:
1) It requires enter to be hit to register the above.
2) It runs both the if & else WriteLines, which I assume is in conjunction with 1)?
How can I amend my code so that when 'y/Y' is pressed, it reads the correct criteria? Or how can I remove the need for Enter to be pressed to proceed?
Used your code below, I tested it and it works.
I moved the char yes = Console.ReadKey() to below the Console.WriteLine().
I changed the name = Console.ReadKey() to Console.ReadLine() because a name is more then 1 key.
string name;
Console.WriteLine("\nYou're awake? It's about time. Not old enough, eh? That sucks. \n\nListen, I really need your help. Would you be interested? Y / N");
char yes = Console.ReadKey();
if (yes == 'y' || yes == 'Y')
{
Console.Write("\nYou will?! Wow, That's fantastic. Right then, where shall I start? \nI know! How about telling me your name? ");
name = Console.ReadLine();
Console.WriteLine("\nAhh yes, now you mention it, I certainly remember you, {0}!", name);
Console.ReadKey(); // I put this here so the program wouldn't exit
}
else
{
Console.WriteLine("\nYou don't want to help me? Oh, that's unfortunate... ");
}
In your code, after Console.WriteLine("\nTo proceed, please press any key..."); you have Console.ReadLine(); which expects you to enter a line in the console (not reading till you press enter) and then in your second method, you're trying to read the console again (but this time for a single key).
Wouldn't it help if you remove the first Console.ReadLine() ?
And then you are trying to get the yes/no answer before asking your question (and before doing another ReadKey.
string result = Console.ReadLine();
if (result.ToUpper().Equals("Y"))
{
//any thing
}
char yes = Console.ReadKey(); // No need for .KeyChar
int age;
Console.Write("Before entering the unknown, could you please confirm your age? ");
age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("");
could be
int age = -1
Console.WriteLine("Before entering the unknown, could you please confirm your age? ");
while (age == -1)
{
if !(int.TryParse(Console.ReadLine(), out age))
{
Console.WriteLine("Please enter a valid age");
}
}
name = Console.ReadKey().ToString();
should be
name = Console.ReadLine();
if (yes == 'y' || yes == 'Y')
could be
if (yes.ToUpper() == "Y")

C# stop user inputting a character/string instead of integer [duplicate]

This question already has answers here:
How can I validate console input as integers?
(10 answers)
Closed 6 years ago.
I am asking users to input a int for their age but the program crashes when they input a string(obviously).
How would I go about allowing them to input a char/string but the program to display a funny message and then quit?.
This is what I have got so far:
Console.WriteLine("Please can you enter your age");
int userage = Convert.ToInt32(Console.ReadLine());
if (userage < 16)
{
var underage = new underage();
underage.text();
}
else if (userage>122)
{
Console.WriteLine("No one has ever reached this age and so you can't possibly be this old");
Console.WriteLine("Please enter a different age next time!");
Console.WriteLine("Unless you really are this old, in which case don't work!!");
Console.WriteLine("Press any key to exit the program.\n");
Environment.Exit(0);
}
else if(userage<122)
{
Console.WriteLine("Ah brilliant, you are old enough to use our services\n");
Console.WriteLine("We shall continue as first planned\n");
}
else
{
}
try:
Console.WriteLine("Please can you enter your age");
int userage;
if (int.TryParse(Console.ReadLine(), out userage))
{
//your if block
}
else
{
Console.WriteLine("Your input is funny and I am a funny message\n");
Environment.Exit(0);
}

Categories

Resources