Empty String Input Validation - c#

I've been having trouble on understanding as of why my custom empty string validation method does not work compared when I check for an empty string directly
Validation.EmptyValidation(title,
"Please, do not leave the course title field empty!" +
"\r\nEnter the course title: ");
It does not output the course title in the end, but when I do it this way it does:
while (string.IsNullOrEmpty(title))
{
Console.WriteLine("No empty string: ");
title = Console.ReadLine();
}
Class:
Console.WriteLine("* Create Course *\r\n");
Console.WriteLine("Enter the course title: ");
string title = Console.ReadLine();
while (string.IsNullOrEmpty(title))
{
Console.WriteLine("No empty string: ");
title = Console.ReadLine();
}
Validation.EmptyValidation(title,
"Please, do not leave the course title field empty!" +
"\r\nEnter the course title: ");
Console.WriteLine("\r\nEnter the course description: ");
string description = Console.ReadLine();
Validation.EmptyValidation(description,
"Please, do not leave the course description field empty!" +
"\r\nEnter the course description: ");
Console.WriteLine("\r\nEnter the number of students in the course: ");
=string studentsInput = Console.ReadLine();
int.TryParse(studentsInput, out int students);
CreateCourse(currentCourse, title, description, students);
public static Course CreateCourse (Course _currentCourse, string title string description, int students)
{
Course course = new Course(title, description, students);
_currentCourse = course;
_currentCourse.Title = course.Title;
Console.WriteLine($"\r\nThank you for registering the {_currentCourse.Title} course.\r\n" +
$"\r\nCourse Information" +
$"\r\nTitle: {_currentCourse.Title}" +
$"\r\nDescription: {_currentCourse.Description}" +
$"\r\nStudents: {_currentCourse.Capacity}");
return _currentCourse;
}
Empty Validation Method:
public static string EmptyValidation(string input, string prompt)
{
while (string.IsNullOrEmpty(input))
{
Console.WriteLine(prompt);
input = Console.ReadLine();
}
return input;
}

There is a couple of things going wrong here
// you weren't returning the results
title = Validation.EmptyValidation(title,
"Please, do not leave the course title field empty!" +
"\r\nEnter the course title: ");
Also if you don't need the other validation anymore you are best to remove it
//while (string.IsNullOrEmpty(title))
//{
// Console.WriteLine("No empty string: ");
// title = Console.ReadLine();
// }

Related

How to find and delete duplicates in an user input in c#

I am trying to find duplicates from user inputs. I am trying to add customers with their first name, last name, and phone number. If all three of the information already exists, I want to throw an appropriate message saying {firstname}, {lastname}, and {phonenumber} already exists. Any idea how to do it?
//this code is on functions class.
public bool addCustomer(params)
{
if (numCustomer < maxCustomer)
{
Random rnd = new Random();
int id = rnd.Next(10000, 99999);
clist[numCustomer] = new Customer(params);
numCustomer++;
return true;
}
return false;
}
//Menu class to prompts user to choose an option
switch (input)
{
case 1: // Add Customer
Console.Clear();
string fName;
string lName;
long phone;
Console.WriteLine("Adding new customer...\nPlease enter the following:");
Console.Write("First Name: ");
fName = Console.ReadLine();
Console.Write("Last Name: ");
lName = Console.ReadLine();
Console.Write("Phone Number (no dashes or spaces): ");
phone = Convert.ToInt64(Console.ReadLine());
m.addCustomer(fName, lName, phone);
Console.WriteLine("\nPress any key to go back to the Customer Menu...");
Console.ReadKey();
customerMenu();
break;
...
}

C# How to pass ARRAY from another Method

I'm a beginner with C# and I need little help. I'm not sure how can I take 'studentArray' from CreateStudent() and use it at ViewAllStudents(). Any help is appreciated!
static void CreateStudent()
{
// User Inputs
Console.WriteLine("Student Name: ");
var name = Console.ReadLine();
Console.WriteLine("Student Surname: ");
var surname = Console.ReadLine();
Console.WriteLine("Student ID: ");
var id = int.Parse(Console.ReadLine());
var student = new Students(name, surname, id); // Student Constructor
// Create Array and Resize it
Students[] studentArray = new Students[] { student };
Array.Resize(ref studentArray, studentArray.Length + 1);
studentArray[studentArray.GetUpperBound(0)] = student;
Console.WriteLine($"Student {student.Name} {student.Surname} with ID {student.StudentId} is successfully created!");
}
static void ViewAllStudents()
{
foreach(var student in studentArray)
{
Console.WriteLine($"\t {student}");
}
}
}
}
Change return type of CreateStudent from void to Students[] and return "studentArray" . Change the parameter type of ViewAllStudents() to "ViewAllStudents(Students[] studentArray )" .I hope the following will work.
static Students[] CreateStudent()
{
// User Inputs
Console.WriteLine("Student Name: ");
var name = Console.ReadLine();
Console.WriteLine("Student Surname: ");
var surname = Console.ReadLine();
Console.WriteLine("Student ID: ");
var id = int.Parse(Console.ReadLine());
var student = new Students(name, surname, id); // Student Constructor
// Create Array and Resize it
Students[] studentArray = new Students[] { student };
Array.Resize(ref studentArray, studentArray.Length + 1);
studentArray[studentArray.GetUpperBound(0)] = student;
Console.WriteLine($"Student {student.Name} {student.Surname} with ID {student.StudentId} is successfully created!");
return studentArray;
}
static void ViewAllStudents(Student[] studentArray)
{
foreach(var student in studentArray)
{
Console.WriteLine($"\t {student}");
}
}

how get customer first name and last name

I'm wondering how to change this code to get first name and last name. My friend and I develop this code but I need to alter this code. There is Customer class as well where I set their properties. So looking for suggestion to alter this:
//Getting No: Of Customers for user wish to enter data.
do
{
needToGetInputFromUser = false;
Console.WriteLine("Please enter customer name");
customerName = Console.ReadLine();
if (customerName.Length < 5 || customerName.Length > 20)
{
Console.WriteLine("Invalid name length, must be between 5 and 20 characters");
Console.WriteLine("Please try again.");
Console.WriteLine(" ");
needToGetInputFromUser = true;
}
else
{
isUserEnteredValidInputData = true;
}
} while (needToGetInputFromUser);
//Getting Account number
My approach is slightly different from everyone else's, Where I ask for first name first, then last name. Here is the Customer class:
class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName { get { return FirstName + " " + LastName; } }
}
Basically I create a Customer object then set the FirstName and LastName based on user input individually like so:
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var customer = new Customer();
customer.FirstName = GetStringValueFromConsole("Customer First Name");
customer.LastName = GetStringValueFromConsole("Customer Last Name");
Console.WriteLine("New Customers name: " + customer.FullName);
Console.WriteLine("Finished");
Console.ReadLine();
}
private static string GetStringValueFromConsole(string valueToAskFor)
{
var needToGetInputFromUser = false;
var stringValue = string.Empty;
do
{
Console.WriteLine("Please enter " + valueToAskFor);
stringValue = Console.ReadLine();
if (stringValue.Length < 5 || stringValue.Length > 20)
{
Console.WriteLine("Invalid \"" + valueToAskFor + "\", must be between 5 and 20 characters");
Console.WriteLine("Please try again.");
Console.WriteLine(" ");
needToGetInputFromUser = true;
}
else
{
needToGetInputFromUser = false;
}
} while (needToGetInputFromUser);
return stringValue;
}
}
}
List<Customer> ListOfCustomer = new List<Customer> ();
do
{
needToGetInputFromUser = false;
Console.WriteLine("Please enter customer name");
customerName = Console.ReadLine();
if (customerName.Length < 5 || customerName.Length > 20)
{
Console.WriteLine("Invalid name length, must be between 5 and 20 characters");
Console.WriteLine("Please try again.");
Console.WriteLine(" ");
needToGetInputFromUser = true;
}
else
{
Customer c = new Customer();
c.Name = customerName;
ListOfCustomer.Add(c);
isUserEnteredValidInputData = true;
}
} while (needToGetInputFromUser);
int CustomerCount = ListOfCustomer.Count;
I assume you get a string like:
Brian Mains
And you want to split by the " " between Brian and Mains, storing it in first/last name in the Customer object right? I think you are trying to do something like:
Customer c = new Customer();
if (customerName.Contains(" ")) {
var terms = customerName.Split(' ');
if (terms.Length == 2) {
c.FirstName = terms[0];
c.LastName = terms[1];
}
else {
//TBD
}
}

How do I return multiple strings from a method in C# [duplicate]

This question already has answers here:
Return multiple values to a method caller
(28 answers)
Closed 6 years ago.
If I have something like:
static string characterName()
{
Console.Write("Name your character: ");
string name = Console.ReadLine();
Console.Write("Is this correct? (Y/N): ");
string nameConfirm = Console.ReadLine();
return nameConfirm;
}
How can I change this so it outputs both nameConfirm and name.
The nameConfirm goes into:
static string stageOne(string nameConfirm)
{
while (nameConfirm != "Y")
nameConfirm = Program.characterName();
if (nameConfirm == "Y")
{
Console.WriteLine("Alright, lets continue.");
nameConfirm = Console.ReadLine();
}
return nameConfirm;
That works fine but I want to be able to call upon the name later if its needed.
There are two ways you could do this that aren't too overkill, the first is to return a string array
static string[] characterName()
{
Console.Write("Name your character: ");
string name = Console.ReadLine();
Console.Write("Is this correct? (Y/N): ");
string nameConfirm = Console.ReadLine();
return new string[]{ nameConfirm, name };
}
This object can then be used like so
string[] names = characterName();
string runStageOne = stageOne(names[0]);
The other way you can do this is to return the nameConfirm variable and use the name variable as a ref, so your method would change to
static string characterName(ref string name)
{
Console.Write("Name your character: ");
string name = Console.ReadLine();
Console.Write("Is this correct? (Y/N): ");
string nameConfirm = Console.ReadLine();
return nameConfirm;
}
And would be called like
string name = "";
string nameConfirmed = characterName(ref name);
By using the ref keyword on your input parameter, it means that when the value of name is changed in the method, that change is reflected outside of it too
You could return a List, a string[], or define a class to represent the result of the method (ie with two string properties)...

Strings-creating "passwords" and "users" (simple with strings)

I need to create a program that will take the users name and "password". If they match the program will say you are in if not, that you're out. I wrote it for 1 user, but I don't know how to make multiple users in one program. My code is below. Thanks for your help :)
Console.WriteLine("Enter your Name");
Console.WriteLine("Enter your Pswrd");
string name = Console.ReadLine();
string pswrd = Console.ReadLine();
string myname = "John";
string mypswrd = "123456";
if (name == myname & pswrd == mypswrd)
{
Console.WriteLine("You are logged in");
}
else
{
Console.WriteLine("Incorrect name or pswrd");
}
Console.ReadLine();
//building the user "database" each pair is <user,password>
Dictionary<string, string> users = new Dictionary<string, string>();
users.Add("John", "123456");
//Here you should add more users in the same way...
//But i would advise reading them from out side the code (SQL database for example).
Console.Writeline("Enter your Name");
string name = Console.ReadLine();
Console.WriteLine("Enter your Passward");
string password = Console.ReadLine();
if (users.ContainsKey(name) && users[name] == password)
{
Console.WriteLine("You are logged in");
}
else
{
Console.WriteLine("Incorrect name or password");
}
Console.ReadLine();
This should work (contains no checks to see if the entered values are correct or not, you should add this kind of safety yourself :)):
Dictionary<string, string> namesToCheck = new Dictionary<string, string>
{
{"John", "123456"},
{"Harry", "someotherpassword"}
};
Console.WriteLine("Enter your Name");
string name = Console.ReadLine();
Console.WriteLine("Enter your Pswrd");
string pswrd = Console.ReadLine();
if (namesToCheck.ContainsKey(name) && namesToCheck[name] == pswrd)
{
Console.WriteLine("You are logged in");
}
else
{
Console.WriteLine("Incorrect name or pswrd");
}
Console.ReadLine();
Why not use arrays?
Console.WriteLine("Enter your Name");
Console.WriteLine("Enter your Pswrd");
string name = Console.ReadLine();
string pswrd = Console.ReadLine();
string[] names = "James,John,Jude".Split(Convert.ToChar(","));
string[] passes = "Pass1, Word2, Password3".Split(Convert.ToChar(","));
for (int i = 0; i<names.Length, i++)
{
if (names[i] == name && passes[i] == pswrd)
{
Console.WriteLine("You are logged in");
}
else
{
Console.WriteLine("Incorrect name or pswrd");
}
}
This will work with the following name/pswrd combinations:
James/Pass1, John/Word2, Jude/Password3
For a bigger list I suggest you use external text file and read lines in each.

Categories

Resources