Is there another alternate way to add Console.WriteLine() in this scenario - c#

In this code, I wish to add a Console.Writeline() after each Console.ReadLine() but how I am implementing the code it is giving me an error. Is there another way how I can add Console.WriteLine() in the instance?
public void CreateAccount()
{
Console.WriteLine("-=-=-=-=-=-=-=-=-=-=-=-=-=-");
Console.WriteLine("Create an Account");
Client createAccount = new Client("Create")
{
NameOfUser = Console.ReadLine(),
SurnameOfUser = Console.ReadLine(),
UserID = Console.ReadLine(),
UserEmail = Console.ReadLine(),
UserHomeAdd = Console.ReadLine(),
UserMobileNumber = int.Parse(Console.ReadLine()),
UsernameField = Console.ReadLine(),
PasswordField = Console.ReadLine(),
CoffePoints = int.Parse(Console.ReadLine())
};
List<Client> accountData = new List<Client>()
{
createAccount
};

You could create a method that prints something and returns Console.ReadLine(), for example:
private static string ReadLine(string writeMessage, bool parseAsInt = false)
{
Console.WriteLine(writeMessage);
var line = Console.ReadLine();
if (parseAsInt)
{
int parseInt = 0;
int.TryParse(line, out parseInt);
line = parseInt.ToString();
}
return line;
}
Then just call it when creating the object:
Client createAccount = new Client("Create")
{
NameOfUser = ReadLine("What's your name?"),
SurnameOfUser = ReadLine("Input your surname"),
[...]
CoffePoints = ReadLine("Coffe points?", true)
};

You can't put WriteLine() between your ReadLine(), because you're initializing properties of your new Client. You can, however, do it like this instead:
public void CreateAccount()
{
Console.WriteLine("-=-=-=-=-=-=-=-=-=-=-=-=-=-");
Console.WriteLine("Create an Account");
Client createAccount = new Client("Create");
Console.WriteLine("Enter NameOfUser ");
createAccount.NameOfUser = Console.ReadLine();
Console.WriteLine("Enter SurnameOfUser ");
createAccount.SurnameOfUser = Console.ReadLine();
Console.WriteLine("Enter UserID ");
createAccount.UserID = Console.ReadLine();
Console.WriteLine("Enter UserEmail ");
createAccount.UserEmail = Console.ReadLine();
Console.WriteLine("Enter UserHomeAdd ");
createAccount.UserHomeAdd = Console.ReadLine();
Console.WriteLine("Enter UserMobileNumber ");
createAccount.UserMobileNumber = int.Parse(Console.ReadLine());
Console.WriteLine("Enter UsernameField ");
createAccount.UsernameField = Console.ReadLine();
Console.WriteLine("Enter PasswordField ");
createAccount.PasswordField = Console.ReadLine();
Console.WriteLine("Enter CoffePoints ");
createAccount.CoffePoints = int.Parse(Console.ReadLine());
List<Client> accountData = new List<Client>()
{
createAccount
};
When you appreciate why this works, I'd recommend to do like Isma suggested (if you've been taught about how to make your own methods yet), to make your code cleaner. I wrote this to help you appreciate why what you wrote wasn't working out. Shorthand property initializers like this:
Something s = new Something(){
Property1 = ReadLine(), //no semicolon here, this is all
Property2 = ReadLine() //one line of code in a=1,b=2,c=3 pattern
};
Cannot have multiple lines of code like this:
Something s = new Something(){
Property1 = WriteLine("Blah"); ReadLine(); //can't put a semicolon here
Property2 = WriteLine("Blah"); ReadLine(); //it HAS to be a comma, because it
Property3 = WriteLine("Blah"); ReadLine(); //HAS to be a single line of code
};
Remember that it is not the return key that defines a new line of code in C#, it's the semicolon. It's simply a language rule that the pattern for setting properties like this is single line, and only one statement can appear on the right hand side of the =
You must either not use the shorthand way (as above) or you must put all the multiple lines of code you want to use into a single method, and then call that method (as Isma suggested)
I'd also like to point out that you said you wanted to "writeline a message after every readline" - note that your program will wait for the user to input anything before it prints your message. Isma's way (and this above) print a message BEFORE asking for a readline, because this is more typically what you'd want to do.
If you really do want it after, then move them to be after (but I guess really you can only be thanking them for their input, and overly thankful things are annoying...) so something like this (Isma's way):
private static string ReadLine(string writeMessage)
{
string s = Console.ReadLine();
Console.WriteLine(writeMessage);
return s;
}
or my way:
public void CreateAccount()
{
Console.WriteLine("-=-=-=-=-=-=-=-=-=-=-=-=-=-");
Console.WriteLine("Create an Account");
Client createAccount = new Client("Create");
createAccount.NameOfUser = Console.ReadLine();
Console.WriteLine("Thanks for entering NameOfUser..");

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;
...
}

Empty String Input Validation

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();
// }

What is the error with the input of the string that it causes nullreferenceexception?

The problem is with the else case, I have commented on the problem lines
static void Main(string[] args)
{
XMLData xmldataExample = new XMLData();
Usergaz usergazExample = new Usergaz();
UsergazItem usergazitemExample = new UsergazItem();
UsergazItem item = new UsergazItem();
string filename = #"C:\Users\565133\Desktop\test.xml";
Deserialize<XMLData> deserializeobj = new Deserialize<XMLData>();
Console.WriteLine("Choose \n1.Serialization\n2.Deserialization\n3.Deserialize only a token");
//It works when I give tknid input line here
int inp = Console.Read();
string tknid = Console.ReadLine();//It doesn't work if I get tknid input here
if (inp == 1)
{
usergazitemExample.getusergazitem();
usergazExample.getusergaz();
usergazExample.gazitem.Add(usergazitemExample);
xmldataExample.getxmldata();
xmldataExample.gazset.Add(usergazExample);
serial(xmldataExample, filename);
Console.WriteLine("Its done");
Console.ReadKey();
}
else if (inp == 2)
{
Console.WriteLine("Getting data from xml file");
// Deserialize<XMLData> deserializeobj = new Deserialize<XMLData>();
xmldataExample = deserializeobj.deserializefunction(filename);
List<Usergaz> samplelist = new List<Usergaz>();
samplelist = xmldataExample.gazset;
MTable.initialize();
MTable.usergazzetterset.Add(xmldataExample.updatedtime, samplelist);
Console.WriteLine("Deserialization complete, check the object");
Console.ReadKey();
}
In this else case, I'm filtering using tknid, but even before I input tknid from the user, I get nullreference exception saying the 'item' object is null.
I get the exception pointed to the Console.WriteLine Line
else
{
//Console.WriteLine("Getting only a specific token Enter the token id");
//string tknid;
//tknid = Console.ReadLine();
//I intended to give tknid input here, but I cannot do it...
//Console.WriteLine(tknid);
//Console.ReadKey();
//string tknid = "3"; Initializing tknid with this statement works fine
item = deserializeobj.deserializefunction(filename).gazset[0].gazitem.Where(X => X.id == tknid).FirstOrDefault();
Console.WriteLine("The value for the token id {0} is {1}", tknid,item.val);
Console.ReadKey();
}
}
I have got the solution, the problem was not with if..else statement, it's with Console.Read().
I replaced int inp = Console.Read() with int inp = int.Parse(Console.ReadLine()) and it works fine.
Now I understand how Console.Read() works with the help of an answer I have shared below, but I'll never try to use Console.Read(), and would always use Console.ReadLine().
How Console.Read() works:
https://stackoverflow.com/a/10318917/7114583

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)...

How to loop a Console.ReadLine?

I cannot figure out how to read user-input in a loop (with Console.ReadLine). I'm trying to create a note that lets me store what ever the user inputs, and exits if he types exit.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
Note myNote = new Note();
Note otherNote = new Note();
myNote.addText("Hi there");
Console.WriteLine(myNote.display());
otherNote.addText(Console.ReadLine());
Console.WriteLine(otherNote.display());
if (otherNote = "exit")
{
}
}
}
}
class Note
{
private string text = "";
private DateTime timeStamp = DateTime.Now;
private DateTime modifiedStamp = DateTime.Now;
int maxLength = 10;
public void addText(string sometext)
{
if (text.Length + sometext.Length < maxLength)
{
text += sometext;
modifiedStamp = DateTime.Now;
}
}
public string display()
{
return "Created: " + timeStamp.ToString() + "\n" +
"Modified: " + modifiedStamp.ToString() + "\n" +
"Content: " + text;
}
}
You need List of Notes in order to add as many notes as you want.
Additionally, you need to first save ReadLine input check if the user really asked to exit otherwise keep adding notes.
var myNotes = new List<Note>();
var firstNote = new Note();
firstNote.addText("Hi there");
Note note;
while (true)
{
var input = Console.ReadLine();
if (input.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
break;
}
note = new Note();
note.addText(input);
myNotes.Add(note);
}
The general format is to use something like this (a while loop with a break condition):
// put code above while loop that only needs to be executed once
while (true) {
// get the user input for every iteration, allowing to exit at will
String line = Console.ReadLine();
if (line.Equals("exit")) {
// exit the method.
return; // use "break" if you just want to exit the loop
}
// this is what will happen in the loop body since we didn't exit
// put whatever note stuff you want to execute again and again in here
}
You'll want to edit what goes into the body of this loop depending on what exactly you want done with your note instances. But generally, you repeatedly prompt a user for input until some condition is met and then you break out of the loop. You may decided that condition (e.g. "enter 10 notes"; "type exit"; etc.)
Per #n0rd's comment, here's how a do...while loop could work:
string input;
var myNotes = new List<Note>();
do{
input = Console.ReadLine();
if (!input.Equals("exit", StringComparison.OrdinalIgnoreCase)){
var note = new Note();
note.addText(input);
myNotes.Add(note);
}
} while (!input.Equals("exit", StringComparison.OrdinalIgnoreCase));
To loop Console.ReadLine() you can use this
`List<string> al = new List<string>(); //list to store string values
while(true)
{
string f = Console.ReadLine();
if(f == null) //check if string is null or not
{
break;
}
else
al.Add(f); //add strings to list
}`
One way to do it is this:
List<string> simpleList = new List<string> { "Alpha", "Bravo", "Charlie", "Delta", "Echo" }; //Dummy data source
Console.WriteLine("Enter a call sign to find in the list. Press X to exit: "); //Prompt
string callSign;
string exitKey = "x";
while ((callSign = Console.ReadLine().ToLower()) != exitKey)
{ //This is where the "Magic" happens
if (simpleList.Contains(callSign))
{
Console.WriteLine($"\"{callSign}\" exists in our simple list");//Output should the list contain our entry
Console.WriteLine(""); //Not really relevant, just needed to added spacing between input and output
}
else
{
Console.WriteLine($"\"{callSign}\" does not exist in our simple list"); //Output should the list not contain our entry
}
Console.WriteLine("");
Console.WriteLine("Enter a call sign to find in the list. Press X to exit: ");//Prompt
}
The line:
while ((callSign = Console.ReadLine().ToLower()) != exitKey) {
...
is where the loop happens. If the entry does not equal the exitKey, the steps are repeated.

Categories

Resources