Add a second command that calls another method? - c#

I'm remaking a text-based adventure game. During the character creation, I'd like for the user, at any time, to type 'skillset' and list all the traits that a specific race has. I've tried for a couple hours and can't seem to figure it out.
This is my character creation class.
public string userCommand_SeachSkill;
SkillSet searchSkill = new SkillSet();
public void Create_Character()
{
// CHOOSE GENDER //
do
{
validate = 0;
Console.Clear();
Console.Write("Are you male or female? (f/m): ");
Sex = Console.ReadLine().ToUpper();
if (Sex == "M" || Sex == "F")
{
validate = 1;
}
else if (Sex != "M" || Sex != "F")
{
Console.WriteLine("You must enter 'm' or 'f'");
}
} while (validate == 0);
And this is my Skill Set Class. Everything in the if/else statements are methods to print the traits of a race to the console. Let me know if there is anything else I can add to better ask my question. Thank you in advance! :)
ClassAttributes classes = new ClassAttributes();
Character character = new Character();
skillset = Console.ReadLine().ToUpper();
do
{
validate = 0;
if (skillset == "HUMAN")
{
classes.SkillSetHuman();
}
else if (skillset == "ORC")
{
classes.SkillSetOrc();
}
else if (skillset == "ELF")
{
classes.SkillSetElf();
}
else if (skillset == "EXIT")
{
validate = 1;
character.Create_Character();
}
} while (validate == 0);

I think you're looking for something like an event. C# Console Applications only seem to have one kind of event, it fires when ctrl+c or ctrl+break happens. You could handle your skillset input/output logic in the function handler
You can read more here:
https://msdn.microsoft.com/library/system.console.cancelkeypress(v=vs.110).aspx
If you really need the word to be typed, you could capture everything that is typed in a special function, instead of using regular Console.ReadLine(). Something like this:
public static string CustomReadLine()
{
ConsoleKeyInfo cki;
string capturedInput = "";
while (true)
{
cki = Console.ReadKey(true);
if (cki.Key == ConsoleKey.Enter)
break;
else if (cki.Key == ConsoleKey.Spacebar)
{
capturedInput += " ";
Console.Write(" ");
}
else if (cki.Key == ConsoleKey.Backspace)
{
capturedInput = capturedInput.Remove(capturedInput.Length - 1);
Console.Clear();
Console.Write(capturedInput);
}
else
{
capturedInput += cki.KeyChar;
Console.Write(cki.KeyChar);
}
if (capturedInput.ToUpper().Contains("SKILLSET"))
{
capturedInput = "";
skillsetTyped();
return "";
}
}
return capturedInput;
}
then inside your Create_Character, do
...
do
{
Console.Write("Are you male or female? (f/m): ");
Sex = CustomReadLine();
} while (String.IsNullOrEmpty(sex));
And finally, handle the skillset logic here
protected static void skillsetTyped()
{
Console.Write("\nWrite your skillset capture/display logic here\n");
}
This is just a draft and has some minor bugs, but I believe it's close to what you really want.

Related

C# “String may be null here” but I don't think it can be null

So I wanted to make a sort of “name checker” that’s always had the first letter be capital and the rest lowercase. I got that to work but whenever I got past the name checker and wanted to use the name in future code, it would always say “string may be null here.” I have tried many things like adding a ? But nothing works. I don’t think it can be null but maybe I’m wrong. Here is my code here:
class Program
{
static void Main()
{
string? name, choice;
bool finishnameingcharacter;
finishnamingcharacter = true;
while(finishingnamingcharacter == false)
{
Console.WriteLine("Enter your name");
name = Console.ReadLine();
name = name?.ToLower();
if(name != null)
{
name = char.ToUpper(name[0]) + name.Substring(1);
}
Console.WriteLine("");
Console.WriteLine("Your name is " +name+ ", is that correct?");
Console.WriteLine("");
Console.WriteLine("1: Yes");
Console.WriteLine("2: No");
choice = Console.ReadLine();
if(choice == "1")
{
finishnamingcharacter = 1;
}
if(choice == "2")
{
Console.WriteLine("");
}
else
{
Console.WriteLine("Invalid Claim")
}
}
Console.WriteLine(name);
}
}
The "name" at the bottom is where the error is. If there's any confusion about my question ask me. I tried my best to explain it.
I could not compile your code, so I made some changes
static void Main()
{
var name = string.Empty;
var choice = string.Empty;
do
{
Console.WriteLine("Enter your name");
name = Console.ReadLine();
name = name?.ToLower();
if (name != null && name.Length>1)
name = char.ToUpper(name[0]) + name.Substring(1);
Console.WriteLine("");
Console.WriteLine("Your name is " + name + ", is that correct?");
Console.WriteLine("");
Console.WriteLine("1: Yes");
Console.WriteLine("2: No");
choice = Console.ReadLine();
if (choice == "1") break;
if (choice == "2")Console.WriteLine("");
else Console.WriteLine("Invalid Claim");
} while (true);
Console.WriteLine(name);
}
Why use a nullable string in this software?
You didn't initialize the name at the beginning, if your loop will never run, then the name output line will be NULL. This is what your error points to.
It is better to initialize variables before their first use, as they can be NULL by default (valid for reference types such as classes). For a string, one option would be String.Empty
string name = String.Empty, choice = String.Empty;
These two lines can be combined:
bool finishnameingcharacter;
finishnamingcharacter = true;
// Replaced by
bool finishnameingcharacter = true;
On the next line in the while loop, you check the condition: finishingnamingcharacter == false. The loop checks the condition and only then executes. To execute the loop, you need the condition to be TRUE, but it will not take this value, because earlier you defined the variable finishnamingcharacter = true. true != false. By default you need to define this variable as false
bool finishnameingcharacter = false;
The user can enter an empty string value, so converting it to lowercase immediately doesn't matter, as long as it checks for an empty string. There is a special method for checking if a string is empty: string.IsNullOrEmpty() - it returns true if the string is empty or null.
If the user entered the wrong name, then we need to ask him to enter again, for this, the continue operator is used.
name = Console.ReadLine();
if(string.IsNullOrEmpty(name) || string.IsNullOrWhiteSpace(name))
{
Console.WriteLine("Sorry, your name is empty. Please enter again.")
continue;
}
//So if name is not empty: jOhN
name = name.ToLower(); //john
name = char.ToUpper(name[0]) + name.Substring(1); //John
For boolean values it is better to use reserved words, i.e. instead of finishnamingcharacter = 1 it is better to write finishnamingcharacter = true
Rest of the code looks good. We all took the first steps :)
Full modified code here:
class Program
{
static void Main()
{
string name = String.Empty choice = String.Empty;
bool finishnameingcharacter = false;
while(finishingnamingcharacter == false)
{
Console.WriteLine("Enter your name");
name = Console.ReadLine();
if(string.IsNullOrEmpty(name) || string.IsNullOrWhiteSpace(name))
{
Console.WriteLine("Sorry, your name is empty. Please enter again.")
continue;
}
//So if name is not empty: jOhN
name = name.ToLower(); //john
name = char.ToUpper(name[0]) + name.Substring(1); //John
Console.WriteLine("");
Console.WriteLine("Your name is " +name+ ", is that correct?");
Console.WriteLine("");
Console.WriteLine("1: Yes");
Console.WriteLine("2: No");
choice = Console.ReadLine();
if(choice == "1")
{
finishnamingcharacter = true;
}
else if(choice == "2")
{
Console.WriteLine("");
}
else
{
Console.WriteLine("Invalid Claim")
}
}
Console.WriteLine(name);
}
}
PS There is a special method TextInfo.ToTitleCase() "wAr aNd pEaCe to titlecase: War And Peace" - I advise you to read

Only allowing yes or no as an answer

I am a complete newbie and i am stuck on a small problem
I want the user to only be able to have yes or no as an answer.
This is what I came up with
static public bool askBool(string question)
{
try
{
Console.Write(question);
return Console.ReadLine() == "y";
}
catch (Exception)
{
throw new FormatException("Only y or n Allowed");
}
}
The problem is entering any other letter then 'y' will result in false, how can I best solve this ?
Thank you in advance.
EDIT (from comment question)
try
{
Console.Write(question);
return int.Parse(Console.ReadLine());
}
catch (Exception)
{
throw new FormatException("Please Enter a Number");
}
I doubt if you want an exception to be thrown - there's nothing exceptional if the user puts OK instead of yes; I suggest to keep asking until "yes" or "no" are read:
public static AskBool(string question) {
while (true) {
// If we have a question to ask (the question is not empty one)...
if (!string.IsNotNullOrWhiteSpace(question))
Console.WriteLine(question); // ... ask it
// Trim: let be nice and trim out leading and trailing white spaces
string input = Console.ReadLine().Trim();
// Let's be nice and accept "yes", "YES", "Y" etc.
if (string.Equals(input, "y", StringComparison.OrdinalIgnoreCase) ||
string.Equals(input, "yes", StringComparison.OrdinalIgnoreCase))
return true;
else if (string.Equals(input, "n", StringComparison.OrdinalIgnoreCase) ||
string.Equals(input, "no", StringComparison.OrdinalIgnoreCase))
return false;
// In case of wrong user input, let's give a hint to the user
Console.WriteLine("Please, answer yes or no (y/n)");
}
}
Here the method will only return true or false if user has entered true or false.If user enters any word the loop will just continue to ask him for input until he enters y or n
you can give it a try by doing following changes
static public bool askBool(string question)
{
bool boolToReturn = false;
Console.Write(question);
while (true)
{
string ans = Console.ReadLine();
if (ans != null && ans == "y")
{
boolToReturn = true;
break;
}
else if ( ans != null && ans == "n")
{
boolToReturn = false;
break;
}
else
{
Console.Write("Only y or n Allowed");
}
}
return boolToReturn;
}`
Answer to second question:-
`
public static int askInt(string question)
{
Int intToReturn = false;
Console.Write(question);
while (true)
{
string ans = Console.ReadLine();
if (int.TryParse(and,out intToreturn))
break;
else
Console.Write("Only number Allowed");
}
return intToReturn;
}`
A bit more simplified version of Dmitry's answer with switch (what I normally do for this kind of scenarios):
static public bool askBool(string question)
{
while(true)
{
Console.Clear();
Console.Write(question);
var input = Console.ReadLine().Trim().ToLowerInvariant();
switch (input)
{
case "y":
case "yes": return true;
case "n":
case "no": return false;
}
}
}
Also I'd consider changing .ReadLine() to .ReadKey() because what we really need here is just 'y' or 'n'... One key is enough.
We use Exceptions mostly for scenarios when unexpected value will lead to some error. We don't throw an exception when we expect user to enter rubbish values and handle them.
You want to throw the exception, not catch it. Example:
static public bool askBool(string question)
{
Console.Write(question);
var input = Console.ReadLine();
if (input == "y")
{
return true;
}
else if(input == "n")
{
return false;
}
else//It's not y or n: throw the exception.
{
throw new FormatException("Only y or n Allowed");
}
}
Of course, you must then capture the 'FormatException' where you call this method.
Something like this?
if (Console.ReadLine() == "y")
{
return true;
}
else if (Console.ReadLine() == "n")
{
return false;
}
else {
throw new Exception("only y and n allowed...");
}
Here another idea:
public static bool ReadUserYesOrNo()
{
bool userSaysYes = true;
Console.Write("Y\b");
bool done = false;
while (!done)
{
ConsoleKeyInfo keyPressed = Console.ReadKey(true); // intercept: true so no characters are printed
switch (keyPressed.Key) {
case ConsoleKey.Y:
Console.Write("Y\b"); // print Y then move cursor back
userSaysYes = true;
break;
case ConsoleKey.N:
Console.Write("N\b"); // print N then move cursor
userSaysYes = false;
break;
case ConsoleKey.Enter:
done = true;
Console.WriteLine();
break;
}
}
return userSaysYes;
}
This will print the default value Y to the console. By pressing Y or N the user can toggle between the two values. The character in the console output will be overwritten. Pressing 'enter' selects the choice and the method returns the result.

How to check user input with if command

Not sure if I'm overlooking something really simple but I'm trying to make a program that allows a user to enter 1 of 2 letters and then run code based on the input. Seems simple enough but I've run into several errors with all the ways I thought this could work. Here is the code:
string name = (Console.ReadLine());
Console.WriteLine("Is " + name + " ok?");
Console.WriteLine("\n(Y)es\n(N)o");
char ansys = Console.ReadKey();
if (ansys = ConsoleKey.Y)
Console.Clear();
else
{
Console.WriteLine();
Console.WriteLine("Enter letters only");
}
I added in the else portion (unfinished)just to get an idea if If i'm going the right direction with the intended goal as well. Would I be able to make an else statement that triggers if neither Y or N is pressed this way?
Well, first of all, you are making an assignment, not comparing:
if (ansys.Key = ConsoleKey.Y)
is wrong, use:
if (ansys.Key == ConsoleKey.X)
== is comparison, = is assignment. Don't confuse them, it may cause serious problems.
For you question, if you simply add an else if statement checking for "No" answer, then else statement won't be triggered if Y or N is pressed. If at least if statement is executed, else statement won't be executed.
Your code should look like:
if (ansys == ConsoleKey.Y) {
// code if yes
}
else if (ansys == ConsoleKey.N) {
// code if no
}
else {
// code if neither
}
Edit:
Since my primary language is not C#, I looked at documentation to check my answer. I figured out that if you use ReadKey() it does not return a ConsoleKey, it returns struct ConsoleKeyInfo. You need to use Key member of the ConsoleKeyInfo to access the pressed key. Please re-check the code.
Try this approach:
ConsoleKeyInfo cki;
cki = Console.ReadKey();
if (cki.Key == ConsoleKey.Y)
{
Console.Clear();
}
else if (cki.Key == Console.N)
{
Console.Clear();
}
else
{
Console.WriteLine();
Console.WriteLine("Enter letters only");
}
You can find th examples here: ReadKey - examples
Try this:
string name = (Console.ReadLine());
Console.WriteLine("Is " + name + " ok?");
Console.WriteLine("\n(Y)es\n(N)o");
var ansys = Console.ReadKey();
if (ansys.KeyChar == 'y' || ansys.KeyChar == 'Y')
{
//Handle yes case
}
if (ansys.KeyChar == 'n' || ansys.KeyChar == 'N')
{
//Handle no case
}
else
{
Console.WriteLine();
Console.WriteLine("Enter letters only");
}
Try this (couldnt test it)
This will ask for the name until the confirmation answer is Y
If the input when asked Y or N is another thing, it will ask again for the name confirmation.
string name = "";
while (name.equals(""))
{
name = (Console.ReadLine());
Console.WriteLine("Is " + name + " ok?");
String answer = "";
while(answer.equals(""))
{
Console.WriteLine("\n(Y)es\n(N)o");
char ansys = Console.ReadKey();
if (ansys == ConsoleKey.Y || ansys == ConsoleKey.N)
{
answer = ansys.ToString();
Console.Clear();
}
else
{
Console.WriteLine();
Console.WriteLine("Enter letters only!!");
}
}
if(!answer.equals("Y"))
name = "";
}
Im not sure if ansys.ToString() is a valid method, and if that returns the "Y" string in case the key pressed was Y

How to check if registration number includes string - c# console app

This is my homework and i've been trying to resolve it but i just can't figure it out.
I need to create records of students that are involved into some class and i need to order them by registration number, name, etc...
Everything works fine, but i do not know, how to check if the registration number includes E in it.
This is what i need to type in:
Name : Mark
Last Name : Markson
Registration Number : E111111
Date of Birth: 1990
My code
do
{
Console.WriteLine("Enter reg number:");
newStudent.regNumber = Console.ReadLine();
} while (newStudent.regNumber.Length != 8 && newStudent.regNumber[0] == 'E');
My problem
If i type in reg number : B111111, it says user added, instead of "wrong reg number"
Please help. Where did i go wrong?
Important
I can use only basic functions from .net library and use of complex functions like - sorting, searching charaters and things like that is strictly forbidden.
do
{
Student newStudent = new Student();
Console.WriteLine("Enter reg. number: ");
newStudent.regNumber = Console.ReadLine();
if (newStudent.regNumber.Length != 8)
{
Console.WriteLine("Registration number should has a length of 8 characters");
}
else
{
bool hasE = false;
for(int i = 0 ; i < newStudent.regNumber.Length; i++)
{
if(newStudent.regNumber[i] == 'E')
{
hasE = true;
break;
}
}
if(hasE == true)
{
Console.WriteLine("Registration number correct :)");
}
else
{
Console.WriteLine("Registration number does not contain E");
}
}
}
while(true);
do {
Console.WriteLine("Enter reg. number: ");
newStudent.regNumber = Console.ReadLine();
if (newStudent.regNumber.Length == 7 && newStudent.regNumber[0] == 'E'){
break;
}
else
{
Console.WriteLine("wrong reg number");
}
} while (true);
there is no while do loop in C#,
Do while loop is like that, but it will not work for you
do
{
// your code
} while (newStudent.regNumber.Length != 8 && newStudent.regNumber[0] == 'E');
Try by using StartWith function of string class.
while (true)
{
Console.WriteLine("Enter reg. number: ");
newStudent.regNumber = Console.ReadLine();
if (newStudent.regNumber.Length != 8 && newStudent.regNumber.StartWith("E"))
{
break;
}
else
{
Console.WriteLine("wrong reg number");
}
}

Why does the `Console.Read()` keep jumping to another spot?

I have a method that is used to ask which way a person would like to go in a Console game.
Afformentioned method:
private static void dirChoose()
{
Console.SetCursorPosition(0, 7);
Console.WriteLine("A mysterious voice says \"Which way will you go?\"");
Console.WriteLine("Type");
if (curLeft == false) { Console.WriteLine("(L)eft "); }
if (curUp == false) { Console.WriteLine("(U)p "); }
if (curRight == false) { Console.WriteLine("(R)ight "); }
if (curDown == false) { Console.WriteLine("(D)own "); }
Console.SetCursorPosition(49, 7);
userDirInput = Convert.ToChar(Console.Read());
Console.SetCursorPosition(0, 13);
Console.Write("read as " + userDirInput);
if (userDirInput == 'u' || userDirInput == 'U') { reDir = 1; userDirInput = 'y'; }//up
else if (userDirInput == 'd' || userDirInput == 'D') { reDir = 3; userDirInput = 'y'; }//down
else if (userDirInput == 'l' || userDirInput == 'L') { reDir = 0; userDirInput = 'y'; }//left
else if (userDirInput == 'r' || userDirInput == 'R') { reDir = 2; userDirInput = 'y'; }//right
else//anything besides
{
Console.SetCursorPosition(0, 14);
Console.WriteLine("You entered an incorrect direction. Please try again.");
Console.SetCursorPosition(rWALL_STOP - 1, 3);
doneBool = false;
t.Elapsed += right;
t.Start();
}
}//dirChoose()
When answering the question of "Which way will you go?" it is SUPPOSED to read the first character that is entered. So were you to type the whole word "left" or "right" then it would have read 'l' and 'r'. Then it is supposed to change a number and let it do what its supposed to do. For some odd reason it jump to the second after reading the first, so it then adds the appropiate method to the timer and continues on its way.
Note:
static Timer t = new Timer(16);
public static char userDirInput { get; set; }
public static bool curLeft { get; set; }
public static bool curUp { get; set; }
public static bool curRight { get; set; }
public static bool curDown { get; set; }
public static bool doneBool{ get; set; }
So my question is "Why is the cursor jumping to the second character after the first? How do I fix it?"
You could read the key as follows. Passing a value of false to the ReadKey() will echo the entered value back on the screen.
ConsoleKeyInfo cki = Console.ReadKey(false);
userDirInput = cki.KeyChar;
instead of
userDirInput = Convert.ToChar(Console.Read());
I'm not sure I understand your question, but you seem to misunderstand the behavior of Console.Read(). When you call Console.Read(), you get the next character in the buffer. If the user types "left" and then hits enter, you'll call console read to get the 'l', and then there will be 5 characters left in the buffer. The next call will return 'e', then 'f', then 't', then '\r', then '\n'.
So if the user enters "left\r\n", the second time you call dirChoose(), it will behave as it should for unrecognized input.

Categories

Resources