I've learned how to store a single input of data and return a value based on it.
What I want to do is obtain multiple inputs from the user, then return a result. But how do I define each input?
Like, if I want the first input to be known as 'stock', and the second as 'value', how do I do that?
I hope I explained my question properly.
string stock = Console.ReadLine();
string value = Console.ReadLine();
.. Or am I interpreting your question incorrectly?
Edit: As a response to your comment:
string input = Console.ReadLine(); //enter stock value
string[] parts = input.split(new String[]{ " " });
stock = parts[1];
value = parts[2];
If you wish to actually define a "new" variable named "stock" and give it the value "value", you should look into System.Collections.Generic.Dictionary<key, value>
If #ItzWarty's answer isn't quite what you want, this would allow your users to enter multiple values in one line:
string line = Console.ReadLine();
//whatever chars you wish to split on...
string[] inputs = line.Split(new char[] {' ', ',', ';'});
string stock = inputs[0];
string value = inputs[1];
You can try this code:
string name = String.Empty;
string department = String.Empty;
int age = 0;
Console.WriteLine("Please, enter the name of your employee, then press ENTER");
name = Console.ReadLine();
Console.WriteLine("Please, enter the department of your employee, then press ENTER");
department = Console.ReadLine();
Console.WriteLine("Please, enter the age of your employee, then press ENTER");
Int32.TryParse(Console.ReadLine(), out age); // default 0
Console.WriteLine("Name: " + name);
Console.WriteLine("Department: " + department);
Console.WriteLine("Age: " + age.ToString());
Related
The expected result is that the user can enter a string and it builds a sentence until the user exits. When my strings are added together there is no space between the strings.
I have tried adding + " " after sentence and it did not work. any ideas? sorry new to c#
public static void Main(string[] args)
{
Console.WriteLine("Each line you enter will be " + "added to a sentence until you " +
"enter EXIT or QUIT");
//Ask the user for input; continue concatenating
//the phrases input until the user enters exit or quit (start with an empty sentence).
string sentence = "";
for (; ; )
{
//Get the next line.
Console.WriteLine("Enter a string ");
string line = Console.ReadLine();
//Exit the loop if the line is a termiantor.
string[] terms = { "EXIT", "exit", "QUIT", "quit" };
//compare the string entered to each of the legal exit commands.
bool quitting = false;
foreach (string term in terms)
{
//Break out of the for loop if you have a match.
if (String.Compare(line, term) == 0)
{
quitting = true;
}
}
if (quitting == true)
{
break;
}
//Otherwise, add it to the sentence.
sentence = String.Concat(sentence, line);
//let the user know how she's doing.
Console.WriteLine("\nyou've entered: " + sentence + " ");
}
Console.WriteLine(" \ntotal sentence:\n " + sentence);
//wait for user to acknowledge results.
Console.WriteLine("Press Enter to terminate...");
Console.Read();
}
Try adding in the space as part of the overloaded methods of String.Concat that joins 3 strings
sentence = String.Concat(sentence, " ", line);
Strings in C# are immutable, meaning you get a new copy of the string every time you change it.
When you do:
Console.WriteLine("\nyou've entered: " + sentence + " ");
You're creating a string that will be passed to Console.WriteLine, but not changing your original sentence variable.
You can simply add the space when you concat the new string with sentence:
sentence = String.Concat(sentence, line, " ");
String.Concat(sentence, " " + line);
Console.WriteLine("What name would you like to be known as?");
string usernameforscore = Console.ReadLine();
int classicscore = 0;
string path = "";
File.AppendAllText(path, (usernameforscore + " " + classicscore + Environment.NewLine));
So essentially this will write a name and a score to a file one line after another, I want to add some kind of validation that checks if someone's entered username is in the file, it will then override that entire line with the new username and score data.
"classicsscore" references the score of the user, stored as an integer previously. It is then placed into a text file along with the person's inputting string username i.e. "John 12". What I want is that if a person inputs John as their username, which the score 400, the line would then be replaced with "John 400" and not affect the rest of the text file.
I'm using Visual studio, C# console program.
Apologies if this is a duplicate, couldn't find a specific answer myself.
Im thinking something like this should work for you.
public void AddOrUpdate(string userName, int score)
{
string path = "";
var newLine = userName + " " + score;
var lines = File.ReadAllLines(path);
var wasUpdated = false;
using (var writer = new StreamWriter(path))
{
foreach (var line in lines)
{
var foundUserName = line.Substring(0, line.LastIndexOf(' '));
if (foundUserName == userName)
{
writer.WriteLine(newLine);
wasUpdated = true;
}
else
writer.WriteLine(line);
}
if(!wasUpdated)
writer.WriteLine(newLine);
}
}
But unless you need this specific format for some reason using a database would be a much better option.
I have a text file that contains the following informations :
1 no mobile
2 new mobile
641 SonyEricsson_Sunny_Standard_v09
643 Nokia_6700s_Standard_v09
There are no white spaces in the txt file, the first column is the Mobile ID and the second column is the Mobile Type.
I have written a small code that takes the input from the user (Mobile ID) and it should return the Mobile Type. I used Parse function.
Please not that ID is int and Type is String.
Here is the small code, but I don't know what is missing to get the string which is the mobile type according to the input by the user.
Thanks for your help
int MobileID = 0;
System.Console.WriteLine("Enter Mobile ID in Numbers and press enter");
MobileID = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("You entered the number:" + MobileID + ".");
Console.ReadKey();
StreamReader reader = File.OpenText(#"C:\Robotron\Execution\MobileID_Type.txt");
string line;
while ((line = reader.ReadLine()) != null)
{
string[] fields = line.Split('\t');
int MobileType = Convert.ToInt32(fields[1]);
}
Console.ReadKey();
What is missing in order to get the input from the user as the ID and return the type that corresponds to that ID ?
Something like:
string[] lines = File.ReadAllLines(#"C:\Robotron\Execution\MobileID_Type.txt");
foreach (var line in lines)
{
string[] columns = line.Split('\t');
if(Convert.ToInt32(columns[0]) == MobileId)
{
return columns[1];
}
}
just chnage the line : int MobileType = Convert.ToInt32(fields[1]);
by : string MobileType = fields[1].ToString();
This will work for you.
int MobileID = 0;
System.Console.WriteLine("Enter Mobile ID in Numbers and press enter");
MobileID = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("You entered the number:" + MobileID.ToString + ".");
Console.ReadKey();
StreamReader reader = File.OpenText("C:\\Robotron\\Execution\\MobileID_Type.txt");
string line = null;
while (reader.Peek != -1) {
line = reader.ReadLine();
string[] fields = line.Split(ControlChars.Tab);
if (MobileID == Convert.ToInt32(fields(0))) {
Console.WriteLine("Mobile Type is:" + fields(1).ToString);
break; // TODO: might not be correct. Was : Exit Do
}
}
Console.ReadKey();
If I have a name consists of more than one part separated by a space, and I want to get:
the first name + " " + the last name.
Is there any way to do that.
No rules except that the names separated by a space.
There are any number of parts.
Example:
john depp lennon
To:
john lennon
string sString = "john depp lennon";
string[] sArray = sString.Split(' ');
string sStartEnd = sArray[0] + " " + sArray[sArray.Count()-1]; // "john lennon"
Since you mentioned LINQ in the tags, I'll get you that, skipping validation for entering one part (only "Johm") or entering nothing at all, that will be:
Ensure you have:
using System.Linq;
Then:
var nameParts = name.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var fullName = string.Format("{0} {1}", nameParts.First(), nameParts.Last());
Thise will do the job for the happy path
If we want to check for edge cases, we can add extra checks:
static string GetName(string nameEntry)
{
// assuming .NET 4, or use string.IsNullOrEmpty(),
// as we are protected later from white space-only text
if(string.IsNullOrWhiteSpace(nameEntry))
return string.Empty; // Or throw error. Your choice
var nameParts = nameEntry.Split(new[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
if(!nameParts.Any()) return string.Empty(); // Or throw error. Your choice
if(nameParts.Length == 1)
return nameParts.First();
var fullName = string.Format("{0} {1}", nameParts.First(), nameParts.Last());
return fullName;
}
string str = "john depp lennon";
string[] data = str.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
string result = string.Format("{0} {1}", data.First(), data.Last());
I have already been able to split a first name and a last name. But the problem I am having is if someone decides to type in a middle initial or a middle name? Anyone know how I can go about doing this?
Here is the code I have so far:
//Name Split
var fullname = strTextBox;
var names = fullname.Split(' ');
label3.Text = names[0];
label5.Text = names[1] + " " + names[2];
This code works if the person types in a middle initial and a a last name. But is the user only types in a first and last name, the names[2] gives me the error since it cannot find another partition.
I would say that I have spent at least 10 hours trying to figure out a conditional to get this to work, but have not gotten it yet.
Here is one of the many conditionals I have tried:
//Name Split
var fullname = strTextBox;
var names = fullname.Split(' ');
if (fullname.Contains (> 1 (' '))
{
label3.Text = names[0]; // first
label5.Text = names[1] + " " + names[2]; // middle initial
}
else
{
label3.Text = names[0];
label5.Text = names[1];
}
Personally I'd go with a seperate text box for each piece of data I want to collect.
The main reason being that you can't accurately predict what the user is going to enter into your "fullname" text box. There's just too many variations.
Consider:
Jamie Dixon
Jamie O Dixon
Dixon, Jamie O
Dixon, Jamie
Jamie O P J Dixon
While there are a finite number of combinations, what you can't really predict is how much and in what order the user will enter the details.
It's not a nice solution what you got, would split it up into two text boxes, but if you want this should bring the desired effect:
var fullname = strTextBox;
var names = fullname.Split(' ');
if(names.Count()<2)
{
// throw an error here, because user did not enter first + lastname
}
label3.Text = names[0];
label5.Text = (names.Count() > 2 ? names[1] + " " + names[2] : names[1]);
try this:
label5.Text = string.Format("{0} {1}", (names.Length == 2 ? "" : names[1]),
names.Last()).Trim();
Try this. This will help whatever names you have at the end.
//string fullname = "";
//string fullname = "first";
//string fullname = "first last";
string fullname = "first middle last";
//string fullname = "first middle last extra-last";
string[] names = fullname.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
if (names.Length > 0)
{
string firstName = names[0];
string lastNameWithInitial = string.Join(" ", names, 1, names.Length - 1);
}