Creating lists with loops by an user in C# - c#

So I want to make a list of names. I want this list to go on until user inputs 0 to quit, after user types 0 I want all names to be displayed. You probably see what I'm trying to do from the code below...that "typedName" is there just so you see what I'm trying to do.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string>();
Console.WriteLine("Type in 0 to end.");
bool over = false;
while (over != true)
{
names.Add(Console.ReadLine());
if(typedName == "0")
{
over = true;
}
}
Console.WriteLine("Entered names : ");
names.ForEach(Console.WriteLine);
Console.ReadLine();
}
}
}

First you need the typedName to be captured and then check if it is equal to 0.
if it is not add it to the list
List<string> names = new List<string>();
Console.WriteLine("Type in 0 to end.");
while (true)
{
var typedName = Console.ReadLine();
if (typedName.Equals("0"))
{
break;
}
names.Add(typedName);
}
Console.WriteLine("Entered names : ");
foreach(var name in names)
{
Console.WriteLine(name);
}
Console.ReadLine();

if(typedName == "0")
Well, what is typedName? Or what should it be? I suspect it should be the input entered by the user, something like this:
var typedName = Console.ReadLine();
You can then add it to the list by using that variable:
names.Add(typedName);
And compare it with "0" as you already do, etc.

your code is not complete that is why is not working...
you are missing the most important part:
populate the list if and only if typedName != "0"
while (!over)
{
var typedName =Console.ReadLine();
if(typedName == "0")
{
over = true;
}else
{
Console.WriteLine("Enter a name... ");
names.Add(Console.ReadLine());
}
...
}

Related

Compare 1st then 2nd then 3rd column of Text File

I'm making a Quizlet Type program and need help comparing text files. I have written
Hello, Hallo
Dog, Hund
Cat, Katze
That is my Text file. I want my program to compare 1st column
Hello, Hallo
And then after that comparison
Dog, Hund
and after that
Cat, Katze
As you see here I wrote code that compares the first row to the second row. But after that, it just doesn't compare to the second column of the file. I need help comparing to 2nd column then 3rd etc.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test32
{
class Program
{
static void Main(string[] args)
{
string filepath = #"C:\Users\akred\Desktop\testfall2\testfall2\Eng.txt";
bool wantstoguess = true;
int attempt = 0;
bool win = false;
int row = 0;
List<engword> word = new List<engword>();
List<string> lines = File.ReadAllLines(filepath).ToList();
foreach (var line in lines)
{
string[] entries = line.Split(',');
engword newWord = new engword();
//Ew = Englisches Wort
//REw = Richtig Englisches Wort bzw richtige übersetzung
newWord.Ew = entries[0].Trim();
newWord.REw = entries[1].Trim();
word.Add(newWord);
}
foreach (var engword in word)
{
do
{
do
{
Console.WriteLine("What is " + $"{engword.Ew }" + " in English");
attempt++;
string guessed = Console.ReadLine();
try
{
if (guessed == $"{ engword.REw }")
{
Console.WriteLine("Correct");
win = true;
++row;
}
else if ($"{ engword.REw }" != guessed)
{
Console.WriteLine("Incorrect");
}
}
catch
{
Console.WriteLine("Please Write a word");
}
} while (win == false);
if (win == true)
{
Console.WriteLine("You gave guessed it!");
Console.Write("It took you " + attempt + " attempts!");
Console.ReadLine();
}
Console.Write("Do you want to continue? [Yes/No]?");
string answer = Console.ReadLine();
if (answer == "Yes")
wantstoguess = true;
win = false;
if (answer == "No")
wantstoguess = false;
} while (wantstoguess == true);
}
Console.ReadLine();
}
}
}
It seems, that you are looking for a Dictionary, Dictionary<string, string>, e.g.
using System.Linq;
...
Dictionary<string, string> EnToDe = File
.ReadLines(filepath)
.Where(line => !string.IsNullOrWhiteSpace(line))
.Select(line => line.Split(','))
.ToDictionary(pair => pair[0].Trim(),
pair => pair[1].Trim(),
StringComparer.OrdinalIgnoreCase);
You can easily create reversed German - English dictionary as well:
Dictionary<string, string> DeToEn = EnToDe
.ToDictionary(pair => pair.Value,
pair => pair.Key,
StringComparer.OrdinalIgnoreCase);
Now you can easily get words
List<string> englishWords = EnToDe.Keys.ToList();
List<string> deutschWords = EnToDe.Keys.ToList();
and translation
string english = "CAT";
if (EnToDe.TryGetValue(english, out var deutsch))
Console.Write($"English \"{english}\" is German \"{deutsch}\"");
else
Console.Write($"Sorry, Engish \"{english}\" is not found in the dictionary");
Edit: If you want to implement some kind of test where student must translate each word from German into English, you can try a simple loop. First we prepare the words:
string[] germanWords = DeToEn
.Keys
.OrderBy(x => Guid.NewGuid()) // Shuffle
.ToArray();
// words which are difficult to learn and thus should be tested again
HashSet<string> wordsToRepeat = new HashSet<string>();
Then loop over these words:
foreach (string word in germanWords) {
int attempt = 0;
while (true) {
attempt += 1;
Console.WriteLine($"What is {word} in English?");
string guessed = Console.ReadLine().Trim();
if (string.Equals(guessed, DeToEn[word], StringComparison.OrdinalIgnoreCase)) {
Console.WriteLine("You gave guessed it!");
Console.WriteLine($"It took you {attempt} attempts!");
break;
}
Console.WriteLine("Incorrect");
// If the word is too difficult to translate, it should appear again
if (attempt >= 3) // let word be difficult if it takes 3+ attempt to guess it
wordsToRepeat.Add($"{word},{DeToEn[word]}");
}
Console.Write("Do you want to continue? [Yes/No]?");
string answer = Console.ReadLine().Trim();
if (string.Equals(answer, "N", StringComparison.OrdinalIgnoreCase) ||
string.Equals(answer, "NO", StringComparison.OrdinalIgnoreCase))
break;
}
File.WriteAllLines("c:\WordsToRepeat.txt", wordsToRepeat);
The way your code is structured is a bit confusing, but if you see what it is actually doing it will be
for each word
{
until the user opts out
{
until the answer is correct
{
try to guess
}
}
}
Which means you never get to the next word unless the user says they don't want to continue. A better way would be do something like
for each word
{
until the answer is correct
{
try to guess
}
if(does not want to continue)
break;
}
Here break will get you out of the for each word loop
UPDATE
If I understood correctly what you're trying to achieve, you should end up with something like
foreach (var engword in word)
{
// do --> remove this
// {--> remove this
do
{
...
} while (win == false);
if (win == true)//this check is unnessesary, you won't get here unless win is true
{
Console.WriteLine("You gave guessed it!");
Console.Write("It took you " + attempt + " attempts!");
Console.ReadLine();
}
Console.Write("Do you want to continue? [Yes/No]?");
string answer = Console.ReadLine();
//Add this
if (answer == "No")
{
Console.Write("Okay, bye!");
break;
}
win = false;
// if (answer == "No")--> remove this
// wantstoguess = false;--> remove this
//} while (wantstoguess == true); --> remove this
}
You should use Dictionary<string, string> instead of List. Then key of dictionary will be english word and value will be german word.
After you build dictionary from txt file you have to loop the dictionary keys (english words) and you have to compare user's input with dictionary value of current key.
// firstly you have to build dictionary similar this
string filepath = #"C:\Users\akred\Desktop\testfall2\testfall2\Eng.txt";
Dictionary<string, string> myDict = File
.ReadLines(filepath)
.Where(line => !string.IsNullOrWhiteSpace(line))
.Select(line => line.Split(','))
.ToDictionary(words => words[0].Trim(), words => words[1].Trim());
foreach(var item in myDict)
{
// here you have to implement loop for user's input and comparing with value
Console.WriteLine($"What is { item.key } in english?");
string guessed = Console.ReadLine();
if (guessed == item.value)
{
// OK
}
else
{
// fail
}
}

Can't get list to another else if block

My goal is to get the list ,StudentFirstName working into the else if statement below. There is more code but I don't know if it is relevant for this, so just ask and I'll post the rest. I'm really unsure what to do next as there seems to be little info on the specifics of lists and their limits, just started btw so I'd appreciate the help.
if (command == "Add" || command == "add")
{
List<string> StudentFirstName = new List<string>();
List<string> StudentLastName = new List<string>();
List<int> StudentID = new List<int>();
string studentfirstname;
string studentlastname;
int studentid;
Console.Write("Enter first name : ");
studentfirstname = Console.ReadLine();
Console.Write("Enter last name : ");
studentlastname = Console.ReadLine();
Console.Write("Enter student ID : ");
studentid = Convert.ToInt32(Console.ReadLine());
StudentFirstName.Add(studentfirstname);
StudentLastName.Add(studentlastname);
StudentID.Add(studentid);
Console.WriteLine("\nInfo has been saved!");
mainMenu();
}
else if (command == "Remove" || command == "remove")
{
foreach (string student in StudentFirstName)
{
Console.WriteLine(student);
}
}
Whichever variables you want to access in the else need to be declared outside of the if block. Eg
List<string> StudentFirstName; // declare here
if (command.ToLower() == "add")
{
StudentFirstName = new List<string>(); // accessible here
...
}
else if (command.ToUpper() == "REMOVE")
{
foreach (string student in StudentFirstName) // and accessible here
...
}
(As an aside, you can simplify your command string test using ToLower() or ToUpper() as shown.)

the Console.ReadLine() Doesn't set the string as the user input

public static void GetCommand(string room, string[] items)
{
Console.WriteLine("what would you like to do?");
string UserInput = Console.ReadLine();
Console.WriteLine("UserInput1: ", UserInput);
UserInput = UserInput.ToLower();
string[] uIn = UserInput.Split();
Console.WriteLine("UserInput2: ",uIn);
if (uIn[0] == "get")
{
get(room, items, uIn);
GetCommand(room,items);
}
if (uIn[0] == "search")
{
search(room, uIn);
}
if (uIn[0]== "north" ^ uIn[0] == "south" ^ uIn[0] == "east" ^ uIn[0] == "west")
{
Console.WriteLine(":::", uIn[0]);
move(room, uIn[0]);
}
if (uIn[0] == "test")
{
test();
}
if (uIn[0] == "clear")
{
Console.Clear();
}
}
I'm not sure why the UserInput is null and why the seeming simple user input isn't working. I am very new to c# so the code isn't good, sorry in advance.
Your UserInput isn't null it's the printing problem...
When you print you can do it in two ways :
Console.WriteLine("UserInput1 : "+UserInput); //use + not ,
Console.WriteLine("UserInput1 : {0}" , UserInput); //inside the {} u type the position of the parameter {0} is first and {1} is second
Note that when you give parameter you use the ,
The problem you had is that you gave parameter while didn't said to print it (didn't use {0})

Validating String in C#

Hi so im trying to validate my string here so that it does not allow any input that starts with: "911" so if you type: "9 11", "91 1", "9 1 1" it should go through my if statement. It works with "911" but not the others, here's my code:
using System;
using System.Collections.Generic;
namespace Phone_List
{
class Program
{
static void Main(string[] args)
{
var phoneList = new List<string>();
string input;
Console.WriteLine("Input: ");
while ((input = Console.ReadLine()) != "")
{
phoneList.Add(input);
for (int i = 0; i < phoneList.Count; i++)
{
if (phoneList[i].Substring(0, 3) == "911")
{
input.StartsWith("9 11");
input.StartsWith("9 1 1");
input.StartsWith("91 1");
Console.WriteLine("NO");
Console.ReadLine();
return;
}
else
{
Console.WriteLine("YES");
Console.ReadLine();
return;
}
}
}
}
}
}
As you can see I am trying to use "input.StartsWith("9 11");" but it does not work...
You could use the Replace method of String; the condition you describe can be formulated as follows.
input.Replace(" ", "").StartsWith("911")
Use regular expressions for checks like this.
For example:
Regex.IsMatch(input, "^\\s*9\\s*1\\s*1");
This regex matches all strings that include whitespaces in front of and between "911".
Use the following to check if the string starts with "911":
First create a copy from the input string but without any white spaces:
string input_without_white_spaces =
new string(input.ToCharArray().Where(x => !char.IsWhiteSpace(x)).ToArray());
Then you can check if the string starts with 911 like this:
if (input_without_white_spaces.StartsWith("911"))
{
...
}
bool valid = s.StartsWith("911") ||
!string.Join("",s.Split()).StartsWith("911");

Loop through list, match word call description from list

I am having a problem constructing a loop WHICH will COMPARE a VAR(userSelection) against the name ITEMS in my LIST(Listings). The goal is that if userSelection MATCHES name, getDescription will Console.WriteLine the GetDefinition and display the definition of the word in the list matched. Most of my code is working, and i've been working on this assignment for a week.
I'm very much a newb, please assume I know nothing. All help is appreciated. I think this would be a while loop, but i've played with all the loops now and am lost and confused. I'm a newb, please use small words and be as detailed as you can afford to be. It's greatly appreciated. Thank you.
My C# Program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;// Needed for Streaming...
using System.IO;// Needed for Streaming...
namespace a090___StreamReader_DictionarySearch
{
class Program
{
private const String FILE_NAME = "dictionary.txt";//establish text file instance
public void Play()
{
do
{
DisplayTitle();
List<Listing> items = LoadListings();//create a list of WordDef objects
Console.Write(string.Join(" | ", items.Select(x => x.GetName()))); //Console.Write("\b \b");// Backspace would also of worked
DisplayText("\n\nPlease enter a word from the selections about to see it's definition");// Nice use of PROMPT
String userSelection = Console.ReadLine().ToLower();//Capture input
//loop through all of the listings, and compare each one to userSelection
//Then once it equals print definition
bool found = false;
foreach (Listing item in items)
{
if (userSelection == item.GetName())
{
Console.WriteLine("You selected: " + userSelection +
"\nWhich Means: " + item.GetDefinition());
found = true;
break;
}
}
if (!found)
{ Console.WriteLine("I'm sorry, I don't have a match for that."); }
} while (PlayAgain());
Salutation();
}
//ToolBox -- my program specific tools
public List<Listing> LoadListings()//load entries display as list
{
StreamReader fileIn = new StreamReader(FILE_NAME);
List<Listing> entry = new List<Listing>();
//loop through every line of the file
while (!fileIn.EndOfStream)
{
String line = fileIn.ReadLine();
String[] pieces = line.Split(':');
if (pieces.Length < 1) continue;//error handling - set to length of text items
Listing myListing = new Listing(pieces[0], pieces[1]);
entry.Add(myListing);
}
fileIn.Close(); return entry;
}
//MaxBox -- my useful tools
public void DisplayText(String StringNameIs)
{ Console.WriteLine(StringNameIs); }//Where are we?
public Boolean PlayAgain()
{
Console.Write("\n\nDo you select again? (y)es or (n)o: ");
String command = Console.ReadLine().ToLower();
if (command == "y" || command == "yes") return true;
return false;
}
public void Salutation()
{ Console.Clear(); Console.WriteLine("Ti Do - oh - oh Ti Do -- So Do!"); } //The last line from the 'do-re-mi' song from the Sound of Music
public void DisplayTitle()
{ Console.Clear(); Console.WriteLine(">>>-- A Dictionary of Sounds --<<< \n"); } //Announce Our Program
static void Main(string[] args)
{
Program DictionaryLookup = new Program();
DictionaryLookup.Play();
Console.Read();
}
}
}
My Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace a090___StreamReader_DictionarySearch
{
class Listing
{
private String name;
private String definition;
public Listing(String name, String definition)
{ this.name = name;
this.definition = definition;}
public String GetName() {return name;}
public String GetDefinition() {return definition; }
}
}
My Text File
Doe: a deer, a female deer
Ray: a drop of golden sun
Me: a name I call myself
Far: a long, long way to run
Sew: a needle pulling thread
La: a note to follow Sew
Tea: a drink with jam and bread
This is untested, but should work, using your existing code.
Assuming each "name" (doe, ray, etc) only occurs once (which they do), then you can use Linq's "SingleOrDefault", which will return null if no match is found.
var selection = items.SingleOrDefault(x => x.GetName() == userSelection);
if (selection == null)
Console.WriteLine("I'm sorry, I don't have a match for that.");
else
Console.WriteLine("You selected: " + userSelection +
"\nWhich Means: " + selection.GetDefinition());
To ignore case during comparison, try modifying the above:
... items.SingleOrDefault(x => String.Compare(x.GetName(), userSelection, true));
There are a number of other things you could change here, but perhaps it won't matter for your assignment. For example, I'd eliminate the private variables in your Listing class and change the public "get" methods into properties:
public String Name { get; private set; }
public String Definition { get; private set; }
Substitute the code
while (true)
{
if (userSelection == name)
{Console.WriteLine("You selected: " + Listing.userSelection() +
"\nWhich Means: " + Listing.items.GetDefinition());}
}
else { Console.WriteLine("I'm sorry, I don't have a match for that."); }
with this
bool found = false;
foreach (Listing item in items)
{
if (userSelection == item.GetName().ToLower())
{
Console.WriteLine("You selected: " + userSelection +
"\nWhich Means: " + item.GetDefinition());
found = true;
break;
}
}
if (!found)
{ Console.WriteLine("I'm sorry, I don't have a match for that."); }
I have use the foreach statement; with this statement you can iterate all items of your collection.
Inside the foreach loop I check if the element Name is equal with the user input, if match I set a bool variable indicating element found.
After the loop if element not found print the message.
NB Obviously this code can be written more concisely with LINQ.

Categories