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

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");
}
}

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

How to ask until the user get specific reply in C#

{
bool stayInLoop = true;
while(stayInLoop)
{
Console.WriteLine("Enter Yor Number");
var PlusA = Console.ReadLine();
Console.WriteLine("Enter Yor Number");
var PlusB = Console.ReadLine();
if(PlusA == ';')
{
stayInLoop = false;
break;
}
else if(PlusB == ';')
{
stayInLoop = false;
break;
}
else
{
Console.WriteLine("Answer =");
Console.WriteLine(PlusA + PlusB);
}
}
}
I want to make a plus calculator, I want to let the user type more then 2 numbers, keep asking for PlusC, PlusD, until they type the symbol ; .
For example the user numbers in PlusA PlusB PlusC and in PlusD, he/she type ; so it should print PlusA + PlusB + PlusC
If he type a number in PlusD, it should ask for PlusE, until he/she type ;, it should sum up all the number before
And I want to auto the process, The program will ask for PlusA to PlusZ itself instead of int it my own, how to do that? (I know I am not saying it clearly, coz i can't find better words)
You want to add numbers until the user enters ;. You should use loops for that. Here's the complete solution that uses a for loop:
switch(exp)
{
case "+":
{
var sum = 0;
for(;;)
{
Console.WriteLine("Enter Yor Number");
var line = Console.ReadLine();
if (line == ";") break;
sum += Convert.ToInt32(line);
}
Console.WriteLine(sum);
break;
}
}
Here we repeat the part inside the loop over and over, accumulating entered numbers into sum variable until the user enters ; - that's when we end the loop with break.
Use a while loop:
switch(exp)
{
case "+":
int sum = 0;
string input = "";
do
{
Console.WriteLine("Enter your number:");
input = Console.ReadLine();
if (input != ";")
sum += int.Parse(input);
} while (input != ";");
Console.WriteLine("Answer =" + sum);
break;
}
You are having problems because you should iterate the code until your exit/end condition is met using the while statement.
switch(exp)
{
case "+":
int mySum = 0;
string userInput = "";
while(userInput != ";")
{
Console.WriteLine("Enter number to add (';' to end the sum):");
userInput = Console.ReadLine();
if (userInput != ";")
{
// Would be interesting checking if entered really is an integer, for example Int32.TyParse()
mySum = mySum + Convert.ToInt32(userInput);
}
}
Console.WriteLine("Answer =" + mySum.ToString());
break;
}
Thankyou for your reply, but is there any way to auto the process, The program will ask for PlusA to PlusZ itself instead of int it my own
bool stayInLoop = true;
while(stayInLoop)
Console.WriteLine("Enter Yor Number");
var PlusA = Console.ReadLine();
Console.WriteLine("Enter Yor Number");
var PlusB = Console.ReadLine();
if(PlusA == ';')
{
stayInLoop = false;
break;
}
else if(PlusB == ';')
{
stayInLoop = false;
break;
}
else
{
Console.WriteLine("Answer =");
Console.WriteLine(PlusA + PlusB);
}
}
and when I run this, it run out 'error CS0019' and 'error CS0139'
What you're looking for is a while() loop.
example:
bool stayInLoop = true;
while(stayInLoop) // basically means (stayInLoop == true)
{
var text = Console.ReadLine();
if(text == ';')
{
stayInLoop = false;
break; // break will stop the loop, but you can also change the variable to false to break the loop.
}
}

Add a second command that calls another method?

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.

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 do i catch an error in a int parsed from string?

I am having trubble finding a way that works and helps to catch an error input. I need to handle if the input is not a 1 or a 2. Like . or a - or just any letter. I have tried catch and well nothing seems to work :/
Someone that have an idea for me to try? I am greatfull for any suggestions!! Thx in advance!
Regards
The code i have written so far looks like this:
console.WriteLine();
Console.Write("Make your choice: ");
int myinput = int.Parse(Console.ReadLine());
if (myinput == 1)
{
FirstEvent();
}
if (myinput == 2)
{
SecondEvent();
}
Usually we use the TryParse methods
int myinput = 0;
if(false == int.TryParse(Console.ReadLine(), out myInput))
// Error, not an integer
Console.WriteLine("Please input 1 or 2");
else
{
if (myinput == 1)
{
FirstEvent();
}
else if (myinput == 2)
{
SecondEvent();
}
else
Console.WriteLine("Please input 1 or 2");
}

Categories

Resources