the Console.ReadLine() Doesn't set the string as the user input - c#

public static void GetCommand(string room, string[] items)
{
Console.WriteLine("what would you like to do?");
string UserInput = Console.ReadLine();
Console.WriteLine("UserInput1: ", UserInput);
UserInput = UserInput.ToLower();
string[] uIn = UserInput.Split();
Console.WriteLine("UserInput2: ",uIn);
if (uIn[0] == "get")
{
get(room, items, uIn);
GetCommand(room,items);
}
if (uIn[0] == "search")
{
search(room, uIn);
}
if (uIn[0]== "north" ^ uIn[0] == "south" ^ uIn[0] == "east" ^ uIn[0] == "west")
{
Console.WriteLine(":::", uIn[0]);
move(room, uIn[0]);
}
if (uIn[0] == "test")
{
test();
}
if (uIn[0] == "clear")
{
Console.Clear();
}
}
I'm not sure why the UserInput is null and why the seeming simple user input isn't working. I am very new to c# so the code isn't good, sorry in advance.

Your UserInput isn't null it's the printing problem...
When you print you can do it in two ways :
Console.WriteLine("UserInput1 : "+UserInput); //use + not ,
Console.WriteLine("UserInput1 : {0}" , UserInput); //inside the {} u type the position of the parameter {0} is first and {1} is second
Note that when you give parameter you use the ,
The problem you had is that you gave parameter while didn't said to print it (didn't use {0})

Related

Can't get list to another else if block

My goal is to get the list ,StudentFirstName working into the else if statement below. There is more code but I don't know if it is relevant for this, so just ask and I'll post the rest. I'm really unsure what to do next as there seems to be little info on the specifics of lists and their limits, just started btw so I'd appreciate the help.
if (command == "Add" || command == "add")
{
List<string> StudentFirstName = new List<string>();
List<string> StudentLastName = new List<string>();
List<int> StudentID = new List<int>();
string studentfirstname;
string studentlastname;
int studentid;
Console.Write("Enter first name : ");
studentfirstname = Console.ReadLine();
Console.Write("Enter last name : ");
studentlastname = Console.ReadLine();
Console.Write("Enter student ID : ");
studentid = Convert.ToInt32(Console.ReadLine());
StudentFirstName.Add(studentfirstname);
StudentLastName.Add(studentlastname);
StudentID.Add(studentid);
Console.WriteLine("\nInfo has been saved!");
mainMenu();
}
else if (command == "Remove" || command == "remove")
{
foreach (string student in StudentFirstName)
{
Console.WriteLine(student);
}
}
Whichever variables you want to access in the else need to be declared outside of the if block. Eg
List<string> StudentFirstName; // declare here
if (command.ToLower() == "add")
{
StudentFirstName = new List<string>(); // accessible here
...
}
else if (command.ToUpper() == "REMOVE")
{
foreach (string student in StudentFirstName) // and accessible here
...
}
(As an aside, you can simplify your command string test using ToLower() or ToUpper() as shown.)

C#, Validating user input for letters and whitespace using boolean

I'm making a program that reverses a string and doesn't allow for anything else than letters and whitespaces, problem is that if i enter a non-valid input and then try to input a valid input it just keeps printing error. I think the problem has something to do with my while loop and the bool result, but i can't figure it out. Please help and thank you!
static void Reverse()
{
string name;
Console.Write("Enter your name: ");
name = Console.ReadLine();
bool result = name.All(c => char.IsWhiteSpace(c) || char.IsLetter(c));
if (Regex.IsMatch(name, #"^[a-zA-Z- ]+$")) // Validates the input for characters and/or spaces
{
char[] charArr = name.ToCharArray();
Array.Reverse(charArr);
string nameRev = new string(charArr);
Console.WriteLine("String is {0}", nameRev);
}
else
{
while (name == String.Empty || result == false) //Should validate the input for whitespace or letter if it doesn't pass the first validation
{
Console.Write("Error! Enter your name, only letters allowed: ");
name = Console.ReadLine();
}
}
You need to wrap your while loop around the hole sequence instead of just having it inside the else statement.
Example:
static void Reverse()
{
// Continues executing as long as result stays false.
bool result;
do
{
string name;
Console.Write("Enter your name: ");
name = Console.ReadLine();
result = name.All(c => char.IsWhiteSpace(c) || char.IsLetter(c));
if (Regex.IsMatch(name, #"^[a-zA-Z- ]+$"))
{
char[] charArr = name.ToCharArray();
Array.Reverse(charArr);
string nameRev = new string(charArr);
Console.WriteLine("String is {0}", nameRev);
}
else
{
Console.WriteLine("Error! Only letters allowed");
}
}
while (!result);
}

How to use global variable for a two condition IF statement in C#

I want user to select from two options which will dictate what a single string says.
Eventually I will construct a sentence with the variables.
It may not make sense much and I'm totally new and doing this for my own enrichment. I know there is probably a lot better ways to construct this but I want to do most of it on my own as I can and have someone look at my finished project and explain what I could do and guide me at that point. First things first though.
I have a working version of this but it doesn't have IF statements with dual conditions. Also I have a class under the project for the construction of the variables and the main class program will generate the output.
class foodReport
{
public void appleSauce()
{
//apple sauce prompt
Console.WriteLine("Did you have apple sauce:");
Console.WriteLine("1. Yes");
Console.WriteLine("2. No");
//capture key
var KP = Console.ReadKey();
Console.Clear();
//yes no if statement
if (KP.Key == ConsoleKey.NumPad1)
{
int hr = 1;
}
if (KP.Key == ConsoleKey.NumPad2)
{
int hr = 2;
}
}
public void whatEaten()
{
//food prompt
Console.WriteLine("What did you eat:");
Console.WriteLine("1. Sandwich");
Console.WriteLine("2. Candy");
//capture key
var KP = Console.ReadKey();
Console.Clear();
//selection if statement
if (KP.Key == ConsoleKey.NumPad1)
{
string food = "A sandwich.";
}
if (KP.Key == ConsoleKey.NumPad2)
{
string food = "Some candy.";
}
}
public void outPut()
{
//WHERE IM HAVING TROUBLE
Console.WriteLine("Desert:");
Console.WriteLine("1. Cookie");
Console.WriteLine("2. Pie");
//capture key
var KP = Console.ReadKey();
Console.Clear();
//selection if statement
if (KP.Key == ConsoleKey.NumPad1 && hr = 1)
{
string report = "You had apple sauce. " + food + " Also, a cookie'";
}
if (KP.Key == ConsoleKey.NumPad2)
{
string report = "You did not have apple sauce. " + food + " Also, a pie'";
}
}
The if (KP.Key == ConsoleKey.NumPad1 && hr = 1) throws error
Operator && cannot be applied to operands of type bool and int
the if (KP.Key == ConsoleKey.NumPad1 && hr = 1) throws error Operator
&& cannot be applied to operands of type bool and int
try "==": if (KP.Key == ConsoleKey.NumPad1 && hr == 1)

Creating lists with loops by an user in C#

So I want to make a list of names. I want this list to go on until user inputs 0 to quit, after user types 0 I want all names to be displayed. You probably see what I'm trying to do from the code below...that "typedName" is there just so you see what I'm trying to do.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string>();
Console.WriteLine("Type in 0 to end.");
bool over = false;
while (over != true)
{
names.Add(Console.ReadLine());
if(typedName == "0")
{
over = true;
}
}
Console.WriteLine("Entered names : ");
names.ForEach(Console.WriteLine);
Console.ReadLine();
}
}
}
First you need the typedName to be captured and then check if it is equal to 0.
if it is not add it to the list
List<string> names = new List<string>();
Console.WriteLine("Type in 0 to end.");
while (true)
{
var typedName = Console.ReadLine();
if (typedName.Equals("0"))
{
break;
}
names.Add(typedName);
}
Console.WriteLine("Entered names : ");
foreach(var name in names)
{
Console.WriteLine(name);
}
Console.ReadLine();
if(typedName == "0")
Well, what is typedName? Or what should it be? I suspect it should be the input entered by the user, something like this:
var typedName = Console.ReadLine();
You can then add it to the list by using that variable:
names.Add(typedName);
And compare it with "0" as you already do, etc.
your code is not complete that is why is not working...
you are missing the most important part:
populate the list if and only if typedName != "0"
while (!over)
{
var typedName =Console.ReadLine();
if(typedName == "0")
{
over = true;
}else
{
Console.WriteLine("Enter a name... ");
names.Add(Console.ReadLine());
}
...
}

How do I make c# ignore letter case

Here I have some simple C# code;
Console.WriteLine("Enter Name");
var name = Console.ReadLine();
if (name == "ashley")
{
Console.WriteLine("You entered: " + name);
}
Console.Read();`
If the user enters ashley it will display "You entered ashley". However if the user enters Ashley or AsHlEy it won't work. What do I need to add to this or how to format so it will ignore the case?
Use string.Equals with an appropriate StringComparison
if (string.Equals(name, "ashley", StringComparison.CurrentCultureIgnoreCase))
{
...
}
If you know that the variable is not null you can also use
if (name.Equals("ashley", StringComparison.CurrentCultureIgnoreCase))
{
...
}
To answer your question in the comments, a do-while loop can be used to loop until the question is answered correctly. The below will loop until the user enters something other than ashley.
string name;
do
{
Console.WriteLine("Enter Name");
name = Console.ReadLine();
}
while (string.Equals(name, "ashley", StringComparison.CurrentCultureIgnoreCase));
You could combine this with a guard variable if you want different messaging:
string name;
bool nameIsCorrect = false;
do
{
Console.WriteLine("Enter Name");
name = Console.ReadLine();
nameIsAshley = string.Equals(name, "ashley", StringComparison.CurrentCultureIgnoreCase);
if (nameIsAshley)
{
Console.WriteLine("Stop entering 'ashley'");
}
}
while (!nameIsAshley);
String.Compare takes a boolean parameter which allows you to ignore casing during comparison:
Console.WriteLine("Enter Name");
var name = Console.ReadLine();
if (String.Compare(name, "ashley", true) == 0)
{
Console.WriteLine("You entered: " + name);
}
Console.Read();
change this:
if (name == "ashley")
to this:
if (name.ToLower() == "ashley")
Use ToLower like this:
Console.WriteLine("Enter Name");
var name = Console.ReadLine();
if (name.ToLower() == "ashley")
{
Console.WriteLine("You entered: " + name);
}
Console.Read();`
You can use the String.ToLower method
your test would be: if (name.ToLower() == "ashley")

Categories