I am trying to make a small cinema program, setting if statements depending on the users age, and one age is 12 A, meaning I have to ask if they are accompanied by an adult
Console.WriteLine(" Enter the number of the film you wish to see :");
int selection = int.Parse(Console.ReadLine());
Console.WriteLine("Enter your age:");
int age = int.Parse(Console.ReadLine());
bool yes = true;
bool no = false;
with the first two options i
have, everything goes smoothly.
if (selection == 3)
{
if (age >= 12)
{
Console.WriteLine("You may enter");
}
else
{
{
Console.WriteLine("Are you accompanied by an adult? Answer yes or no" );
Console.ReadLine();
if (true)
{
Console.WriteLine("You may pass.");
}
else if (false)
{
Console.WriteLine("You are not allowed.");
...
Here, no matter what I input it will go through the first conditional and end there or it is unreachable code if I write Console.ReadLine(); on the else if statement.
Thanks in advance for any help.
Rather than evaluating true, or false which will always give the same answer you need to check what the user wrote back to you by storing it in a variable.
if (age >= 12)
{
Console.WriteLine("You may enter");
}
else
{
string response = null;
while(response != "yes" || response != "no"){
response = Console.ReadLine("Are you accompanied by an adult? Answer yes or no" );
}
if (response == "yes")
{
Console.WriteLine("You may pass.");
}
//Only other way to get here is if they answered, "no" so don't need to check response
else{
Console.WriteLine("You are not allowed.");
}
}
You should check not true or false constants, but actual user input, say bool accompanied:
if (selection == 3) {
if (age >= 12)
Console.WriteLine("You may enter")
else {
Console.WriteLine("Are you accompanied by an adult? Answer yes or no" );
// Trim() - let's be nice and allow user to leave leading/trailing spaces
string input = Console.ReadLine().Trim();
// accompanied if user's input "y" or "yes" (case insensitive)
bool accompanied = "yes".Equals(input, StringComparison.OrdinalIgnoreCase) ||
"y".Equals(input, StringComparison.OrdinalIgnoreCase);
if (accompanied)
Console.WriteLine("You may pass.");
else
Console.WriteLine("You are not allowed.");
}
}
You forgot to receive the value of the adult follow-up question.
Try this:
private static void Main(string[] args)
{
Console.WriteLine(" Enter the number of the film you wish to see :");
int selection = int.Parse(Console.ReadLine());
Console.WriteLine("Enter your age:");
int age = int.Parse(Console.ReadLine());
if (selection == 3)
{
if (age < 12)
{
Console.WriteLine("Are you accompanied by an adult? Answer yes or no");
string isAccompanied = Console.ReadLine();
if (isAccompanied.ToUpper().Equals("NO"))
{
Console.WriteLine("You are not allowed.");
return;
}
Console.WriteLine("You may pass.");
return;
}
Console.WriteLine("You may enter");
return;
}
}
if you want "yes/no", you should store it in a string variable, evaluate if condition according to this variable.
if (selection == 3)
{
if (age >= 12)
{
Console.WriteLine("You may enter");
}
else
{
{
Console.WriteLine("Are you accompanied by an adult? Answer yes or no" );
string res = Console.ReadLine();
if (res == "yes")
{
Console.WriteLine("You may pass.");
}
else if (res == "no")
{
Console.WriteLine("You are not allowed.");
You're reading the input, but not doing anything with it:
Console.ReadLine();
And you are trying to evaluate a hard-coded boolean literal which will never change:
if (true)
Instead, examine what's actually being input. For example:
var userInput = Console.ReadLine();
if (userInput.Equals("yes", StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine("You may pass.");
}
else
{
Console.WriteLine("You are not allowed.");
}
It looks like you are not storing or testing the answer to the question 'Are you accompanied by an adult?'. You need to store the answer from the readline method and test if the answer = yes or no.
IE: amend the top of your file to include a variable to check the age against:-
Console.WriteLine(" Enter the number of the film you wish to see :");
int selection = int.Parse(Console.ReadLine());
Console.WriteLine("Enter your age:");
int age = int.Parse(Console.ReadLine());
bool isUserOldEnough = false;
And then modify your code to something like:-
if (selection == 3)
{
if (age >= 12)
{
Console.WriteLine("You may enter");
}
else
{
Console.WriteLine("Are you accompanied by an adult? Answer yes or no" );
if (Console.ReadLine().ToLower() == "yes") isUserOldEnough = true;
if (isUserOldEnough == true)
{
Console.WriteLine("You may pass.");
}
else
{
Console.WriteLine("You are not allowed.");
}
}
}
Related
so I am pretty new to C# and after learning some fundamentals I tried making a simple program to check for someone's eligibility using if statements.
The program asks for 3 things: Age, Height, and CollegeDegree
You have to be 18 to go to the next question and you have to be taller than 160cm to go to the CollegeDegree question.
Now the program works fine, however looking at it, I come to realize that there are a lot of nested if statements and the code is just messy and unreadable.
What would I need to do to make it cleaner? I tried just doing it as follows
if
else
if
else
However, that causes the issue that if the first condition is not met, so the age is < 18 it just runs the next if statement instead of making the user be ineligible.
Current Code:
static void Main(string[] args)
{
int ageInput;
int heightInput;
bool hasCollegeDegree;
Console.WriteLine("How old are you?");
ageInput = Convert.ToInt32(Console.ReadLine());
if (ageInput >= 18)
{
Console.WriteLine("You are older than 18");
Console.WriteLine("How tall are you?");
heightInput = Convert.ToInt32(Console.ReadLine());
if (heightInput >= 160)
{
Console.WriteLine("You are taller than 160cm");
Console.WriteLine("Do you have a college degree?");
hasCollegeDegree = Convert.ToBoolean(Console.ReadLine());
if (hasCollegeDegree == true)
{
Console.WriteLine("You have a college degree");
Console.WriteLine("You are eligible");
}
else
{
Console.WriteLine("No College Degree");
Console.WriteLine("You are ineligible");
}
}
else
{
Console.WriteLine("You are too short");
}
}
else
{
Console.WriteLine("You are too young");
}
}
You can exit out of the code using a reverse condition. Example:
Console.WriteLine("How old are you?");
int ageInput = Convert.ToInt32(Console.ReadLine());
if (ageInput < 18)
{
Console.WriteLine("You are too young");
return;
}
Console.WriteLine("You are older than 18");
Console.WriteLine("How tall are you?");
int heightInput = Convert.ToInt32(Console.ReadLine());
if (heightInput < 160)
{
Console.WriteLine("You are too short");
return;
}
Console.WriteLine("You are taller than 160cm");
Console.WriteLine("Do you have a college degree?");
bool hasCollegeDegree = Convert.ToBoolean(Console.ReadLine());
if (!hasCollegeDegree)
{
Console.WriteLine("No College Degree");
Console.WriteLine("You are ineligible");
return;
}
Console.WriteLine("You have a college degree");
Console.WriteLine("You are eligible");
I suggest extracting methods to read integer:
private static int ReadInteger(string question) {
while (true) {
if (!string.IsNullOrWhiteSpace(question))
Console.WriteLine(question);
if (int.TryParse(Console.ReadLine(), out int result))
return result;
Console.WriteLine("Sorry, not a valid integer; please, try again.");
}
}
and boolean:
private static HashSet<string> s_Yes =
new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
"Y", "Yes", "T", "True", "OK"
};
private static HashSet<string> s_No =
new HashSet<string>(StringComparer.OrdinalIgnoreCase) {
"N", "No", "F", "False"
};
private static bool ReadBoolean(string question) {
while (true) {
if (!string.IsNullOrWhiteSpace(question))
Console.WriteLine(question);
string input = Console.ReadLine().Trim();
if (s_Yes.Contains(input))
return true;
if (s_No.Contains(input))
return false;
Console.WriteLine("Sorry, not a valid value; please, try again.");
}
}
then you can put
if (ReadInteger("How old are you?") < 18) {
Console.WriteLine("You are too young");
return;
}
Console.WriteLine("You are older than 18");
if (ReadInteger("How tall are you?") < 160) {
Console.WriteLine("You are too short");
return;
}
Console.WriteLine("You are taller than 160cm");
if (!ReadBoolean("Do you have a college degree (Y/N)?")) {
Console.WriteLine("No College Degree");
Console.WriteLine("You are ineligible");
return;
}
Console.WriteLine("You have a college degree");
Console.WriteLine("You are eligible");
A disadvantage with the answers so far using return is that the method is exited and therefore you can't have any code below that point in the same method.
A different approach is to use a COMPOUND boolean statement and combine all the conditions into one boolean expression:
if (ageInput >= 18 && heightInput >= 160 && hasCollegeDegree)
{
Console.WriteLine("Congratulations! You meet the criteria.");
}
else
{
Console.WriteLine("You do not meet the criteria.");
}
This style of check might be useful if you have many different combinations that you need to check for. So the user enters all the information up front and then you can have a whole series of different compound checks to see which combinations they satisfy. Maybe you're checking to see which grants from a list that the user qualifies for.
See Boolean logical operators for more information on &&, ||, and !.
I am new to C# and was playing with the loops, I just want to know how I can set the variable userTarget equal to an integer value in case if the user enters strings, i tried the TryParse method but I don't know if I really understand what I am doing with that.
static void Main()
{
string userChoice = string.Empty;
do
{
Console.WriteLine("Please enter your target?");
int userTarget = int.Parse(Console.ReadLine());
int start = 0;
while (start <= userTarget)
{
Console.Write(start + " ");
start += 2;
}
do
{
Console.WriteLine("Do you want to continue?");
userChoice = Console.ReadLine().ToUpper();
if (userChoice != "YES" && userChoice != "NO")
{
Console.WriteLine("Invalid choice, please say yes or no");
}
} while (userChoice != "YES" && userChoice != "NO");
} while (userChoice == "YES");
}
TryParse is definitely the way to go for user input
Converts the string representation of a number to its 32-bit signed
integer equivalent. A return value indicates whether the operation
succeeded.
Example of continual validation
int userChoice = -1;
...
Console.WriteLine("Please enter your target?");
while (!int.TryParse(Console.ReadLine(), out userTarget))
Console.WriteLine("You had one job, enter a target...");
Console.WriteLine($"You entered : {userChoice}");
//Gender Creation:
while (correct == 0)
{
do
{
Console.Clear();
Console.WriteLine("Please choose a gender from the options below: ");
Console.WriteLine("Male|Female|Random");
Console.Write("Input: ");
Gender = Console.ReadLine().ToUpper();
if (Gender == "MALE")
{
Console.WriteLine("Is this the gender you wish your character to be? Enter Yes/No: ");
Console.Write("Input: ");
Input = Console.ReadLine().ToUpper();
if (Input == "YES")
{
correct = 1;
}
else if (Input == "NO")
{
correct = 0;
}
}
else if (Gender == "FEMALE")
{
Console.WriteLine("Is this the gender you wish your character to be? Enter Yes/No: ");
Console.Write("Input: ");
Input = Console.ReadLine().ToUpper();
if (Input == "YES")
{
correct = 1;
}
else if (Input == "NO")
{
correct = 0;
}
}
else if (Gender == "RANDOM")
{
correct = 2;
}
else
{
Console.WriteLine("ERROR, Please try again.");
Gender = Console.ReadLine().ToUpper();
}
} while (correct == 0);
//Random Gender Creation:
if (correct == 2)
{
do
{
if (randgender == 1)
{
Console.WriteLine("The gender: MALE was randomly chosen");
Console.WriteLine("Is this the gender you wish your character to be? Enter Yes/No: ");
Console.Write("Input: ");
Input = Console.ReadLine().ToUpper();
if (Input == "YES")
{
correct = 1;
Gender = "MALE";
}
else if (Input == "NO")
{
correct = 2;
}
}
else if (randgender == 2)
{
Console.WriteLine("The gender: FEMALE was randomly chosen");
Console.WriteLine("Is this the race you wish your character to be? Enter Yes/No: ");
Console.Write("Input: ");
Input = Console.ReadLine().ToUpper();
if (Input == "YES")
{
correct = 1;
Gender = "FEMALE";
}
else if (Input == "NO")
{
correct = 2;
}
}
} while (correct == 2);
correct = 0;
}
break;
}
When correct = 2 then the gender is being randomly generated, if the user inputs no when being asked if they are happy with the gender the code will just loop the random gender generator over and over constantly saying that the random gender is the same every time as the random number is never changing however when correct = 0 the code will just proceed when no is inputted and when the gender is printed it is just printed as RANDOM as that is the option the user initially chose.
How can I make it go back to the first do while loop to ask the user what gender they want their character to be?
As theMayer suggested, you'll need to break down your app into smaller pieces. There are also a few concepts that you may need to tackle before you can write C#, as such.
This example might help you get a little further along, as it illustrates several ways of achieving better control flow:
static void Main(string[] args)
{
Console.Clear();
var choosenGender = "";
var wasChoiceConfirmed = false;
while (wasChoiceConfirmed == false)
{
choosenGender = PromptForGender();
switch (choosenGender)
{
case "RANDOM":
var randomGender = GenerateRandomGender();
wasChoiceConfirmed = PromptForGenderConfirmation(randomGender, true);
break;
case "MALE":
case "FEMALE":
wasChoiceConfirmed = PromptForGenderConfirmation(choosenGender);
break;
default:
Console.WriteLine("Error, please try again. \n");
break;
}
}
}
static string PromptForGender()
{
Console.Write(
"\nPlease choose a gender from the options below: \n" +
"Male|Female|Random \n" +
"Input:");
return Console.ReadLine().Trim().ToUpper();
}
static bool PromptForGenderConfirmation(string gender, bool wasRandom = false)
{
var randomVerbiage = wasRandom ? "randomly " : "";
Console.Write(
$"\nThe gender: {gender} was {randomVerbiage}chosen \n" +
"Is this the gender you wish your character to be? Enter Yes/No: \n" +
"Input: ");
var confirmed = Console.ReadLine().Trim().ToUpper();
return confirmed == "YES";
}
static string GenerateRandomGender()
{
var randomNumber = new Random();
return randomNumber.Next(0, 1) == 0 ? "FEMALE" : "MALE";
}
I refactored your code so it helps me understand it better. This gives you the result you want and you don't need all those nested loops.
public class Program
{
public static void AskFirstQuestion()
{
Console.Clear();
Console.WriteLine("Please choose a gender from the options below: ");
Console.WriteLine("Male|Female|Random");
Console.Write("Input: ");
var gender = Console.ReadLine()?.ToUpper();
if (gender == "MALE" || gender == "FEMALE")
{
HandleGenderSelection(gender);
}
else if (gender == "RANDOM")
{
HandleRandom();
}
}
private static void HandleRandom()
{
var randomGender = GenerateRandomGender();
Console.WriteLine($"The gender: {randomGender} was randomly chosen");
Console.WriteLine("Is this the race you wish your character to be? Enter Yes/No: ");
Console.Write("Input: ");
var input = Console.ReadLine()?.ToUpper();
switch (input)
{
case "YES":
Console.WriteLine("OK");
break;
case "NO":
AskFirstQuestion();
break;
}
}
private static string GenerateRandomGender()
{
//Have you logic to randomly create gender
return "MALE";
}
private static void HandleGenderSelection(string gender)
{
Console.WriteLine("Is this the gender you wish your character to be? Enter Yes/No: ");
Console.Write("Input: ");
var input = Console.ReadLine()?.ToUpper();
if (input == "YES")
{
Console.WriteLine("OK!");
}
else if (input == "NO")
{
AskFirstQuestion();
}
}
static void Main(string[] args)
{
AskFirstQuestion();
}
}
I have searched stackoverflow and haven't found anything that answers my question. Unfortunately it is not an easy question to word as a search query.
I'm using c# and I have a menu that asks the user to pick an option from 1 - 4. I am validation that the value picked is an integer, but my code breaks whenever I enter a letter or symbol. How do I add the validation for this to? My code currently is as follows.
static void Main(string[] args)
{
DirectoryInfo folderInfo = new DirectoryInfo("C:\\Windows");
FileInfo[] files = folderInfo.GetFiles();
int mainMenuChoice=0;
while ( mainMenuChoice != 1 || mainMenuChoice!= 2 || mainMenuChoice!= 3 || mainMenuChoice!= 4)
{
Console.WriteLine("What would you like to do?");
Console.WriteLine("1. Full File Listing.");
Console.WriteLine("2. Filtered File Listing.");
Console.WriteLine("3. FolderStatistics.");
Console.WriteLine("4. Quit.");
mainMenuChoice = int.Parse(Console.ReadLine());
if (mainMenuChoice == 1)
{
Option1();
}
if (mainMenuChoice == 2)
{
Option2();
}
if (mainMenuChoice == 3)
{
Option3();
}
if (mainMenuChoice == 4)
{
}
else
{
Console.WriteLine("you didnt enter a valid input! try again.");
}
}
Change the reading from the command line to
if(Int32.TryParse(Console.ReadLine(), out mainMenuChoice))
{
if (mainMenuChoice == 1)
Option1();
else if (mainMenuChoice == 2)
Option2();
else if (mainMenuChoice == 3)
Option3();
else if (mainMenuChoice == 4)
Option4();
else
Console.WriteLine("you didnt enter a valid input! try again.");
}
else
{
Console.WriteLine("you didnt enter a valid input! try again.");
}
and repeat the warning message for your user in the else part of the TryParse if.
Int32.TryParse return false when the characters on the command line cannot be converted to an integer and assigned to the out parameter mainMenuChoice.
Use int.TryParse instead:
if (!int.TryParse(Console.ReadLine(), out mainMenuChoice))
{
Console.WriteLine("That's not a number!");
}
...
But in fact, you're never actually using the input as a number, so there's no real need to parse it. You could just leave it as a string:
bool retry;
do
{
retry = false;
Console.WriteLine("What would you like to do?");
Console.WriteLine("1. Full File Listing.");
Console.WriteLine("2. Filtered File Listing.");
Console.WriteLine("3. FolderStatistics.");
Console.WriteLine("4. Quit.");
string mainMenuChoice = Console.ReadLine();
switch(mainMenuChoice)
{
case "1":
Option1();
break;
case "2":
Option2();
break;
case "3":
Option3();
break;
case "4":
break;
default:
Console.WriteLine("You didn't enter a valid input! Try again.");
retry = true;
break;
}
} while(retry);
Also, although this is pretty clear and easy to ready, you don't actually need the retry variable. Although it's a lot less obvious how this works (and I would probably avoid it for that reason), you can structure your loop like this:
do
{
Console.WriteLine("What would you like to do?");
Console.WriteLine("1. Full File Listing.");
Console.WriteLine("2. Filtered File Listing.");
Console.WriteLine("3. FolderStatistics.");
Console.WriteLine("4. Quit.");
string mainMenuChoice = Console.ReadLine();
switch(mainMenuChoice)
{
// same as above
default:
Console.WriteLine("You didn't enter a valid input! Try again.");
continue; // goes back to beginning of the loop
}
break; // exits the loop
} while(true);
while(true)
{
int menuChoice;
string userInput = Console.Readline();
if(Int32.TryParse(userInput, out menuChoice))
{
if(menuChoice >= 1 && menuChoice <= 4)
RunCommand(menuChoice);
else
Console.WriteLine("Enter a number between 1-4");
}
else
Console.WriteLine("A number between 1-4 is required!");
}
Use the TryParse method on Int (details here).
For example:
int menuChoice;
if(!int.TryParse(Console.Readline(),out menuChoice){
Console.WriteLine("The menu choice you made was invalid.");
} else {
//do the rest of your code here
}
I have a problem which I mentioned in the title, just need some help to get rip of this annoying error.
Here's my code:
bool moreEmp;
int arrayplus;
string doitagain;
arrayplus = -1;
string[,] employees = new string[10, 10];
do
{
arrayplus++;
Console.WriteLine("please enter your employee's number");
employees[0, arrayplus] = Console.ReadLine();
Console.ReadLine();
Console.WriteLine("please enter your employee's name");
employees[1, arrayplus] = Console.ReadLine();
Console.ReadLine();
Console.WriteLine("please enter your employee's age");
employees[2, arrayplus] = Console.ReadLine();
Console.ReadLine();
Console.WriteLine("please enter your employee's official position ");
employees[3, arrayplus] = Console.ReadLine();
Console.ReadLine();
Console.WriteLine("please enter your employee's salary");
employees[4, arrayplus] = Console.ReadLine();
Console.ReadLine();
Console.WriteLine("Do you want to add more employees into this list? y or n.");
doitagain = Console.ReadLine();
if (doitagain == "y" || doitagain == "Y")
{
moreEmp = true;
}
else if (doitagain == "n" || doitagain == "N")
{
moreEmp = false;
}
else
{
Console.WriteLine("You have entered an invalid information");
}
}
while (moreEmp == true);
So I actually assigned bool variable with my if statement, I still don't know why I made such a error like this. Thank for reading my question and hopefully you will help me out :D.
You assign a value in the if, and the else if, but not in the else clause. If that final else is hit, the value is never assign to that variable.
Looking at your code, it should probably be assigned a true value in that else. That will fix the problem for you.
Problem is in else block, how do you handle when doitagain is neither n/N or y/Y.
So either use this
else
{
moreEmp = false; //Set this as your requirement
Console.WriteLine("You have entered an invalid information");
}
Or
bool moreEmp = false;
do{
if (doitagain == "y" || doitagain == "Y")
{
moreEmp = true;
}
}while(moreEmp);