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.)
Related
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})
I am currently writing a program where I have to
1) Giving user some options: 1.Search by name? 2. Search by date of birth?
2) If user selects search by name, ask them to put first name and then give the output
3) If user selects search by date of birth, ask them to put date of birth with format (MM/DD/YYYY) and then give the output.
I have to Repeat the options if the validation failed or couldn’t find the data.
I am struggling with the concept of repeating the options. ANy help is extremely appreciated.
My code so far
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Week2Tutorial
{
class Program
class Student
{
public int Id { get; set; }
public string FirstName { get; set; }
public string Lastname { get; set; }
public DateTime DOB { get; set; }
public string Gender { get; set; }
}
static void Main(string[] args)
{
var students = new List<Student>()
{
new Student() { Id = 1,FirstName = "Min Chul",Lastname = "Shin",DOB = new DateTime(2010,01,01),Gender = "Male"},
new Student() { Id = 2,FirstName = "Nicky", Lastname = "Lauren", DOB = new DateTime(2009, 01, 01), Gender = "Female"},
new Student() { Id = 3, FirstName = "Amy", Lastname = "Park", DOB = new DateTime(2008, 01, 01), Gender = "Female" },
new Student() { Id = 4, FirstName = "Aurelie", Lastname = "Adair", DOB = new DateTime(2007, 01, 01), Gender = "Female" }
};
//foreach (var x in students)
//{
// Console.WriteLine("Id = {0}, FirstName = {1}, Lastname = {2}, DOB = {3}, Gender = {4}",x.Id,x.FirstName,x.Lastname,x.DOB,x.Gender);
//}
Console.WriteLine(" Please Choose one of the options:");
Console.WriteLine("1> Search by first name");
Console.WriteLine("2> Search by date of birth");
switch ( Convert.ToInt32(Console.ReadLine()))
{
case 1:
Console.WriteLine("You choose:1");
Console.WriteLine("Type your first name:");
var a = Console.ReadLine();
var case1 = students.Where(x=>x.FirstName==a);
if (case1.Count()!=0)
{
Console.WriteLine("Found! Here are the details:");
foreach (var x in case1)
{
Console.WriteLine("Name: {0}{1} D.O.B:{2} and Gender{3}", x.FirstName, x.Lastname, x.DOB, x.Gender);
}
}
else
{
Console.WriteLine(" Enter the correct information");
}
break;
case 2:
Console.WriteLine("You choose:2");
Console.WriteLine("Enter your Date of Birth in format MM/DD/YYYY:");
var b = DateTime.Parse(Console.ReadLine());
//Console.WriteLine(b);
//Console.ReadLine();
var case2 = students.Where(x => x.DOB == b);
if (case2.Count() != 0)
{
Console.WriteLine("Found! Here are your details");
foreach (var x in case2)
{
Console.WriteLine("Name:{0} {1} DOB:{2} Gender:{3}", x.FirstName, x.Lastname, x.DOB, x.Gender);
}
}
else
{
Console.WriteLine(" Enter the correct information");
}
break;
default:
Console.WriteLine("Please enter the valid option");
break;
}
}
}
}
It can be Done be with do while loop here is the general syntax of do while Loop
do {
code to be executed;
} while (condition is true);
what is do while loop it is an endless loop that is executes the code till the condition is true.
In Your Case we are taking a new varibale temp which is intially zero means no
result if any of your switch case gets true and find results according to user's search query the count of that result will be copied to temp variable now temp no longer have zero value means condition is false means the code will not be executed again
You Just Need to start an endless loop till the condition is true
do{
var temp=0; ///Temporary variable to check the result count
//intially variable b will be zero because INtially result count is zero
Console.WriteLine(" Please Choose one of the options:");
Console.WriteLine("1> Search by first name");
Console.WriteLine("2> Search by date of birth");
switch ( Convert.ToInt32(Console.ReadLine()))
{
case 1:
Console.WriteLine("You choose:1");
Console.WriteLine("Type your first name:");
var a = Console.ReadLine();
var case1 = students.Where(x=>x.FirstName==a);
temp=case1.Count(); //Getting result count in another variable
if (case1.Count()!=0)
{
Console.WriteLine("Found! Here are the details:");
foreach (var x in case1)
{
Console.WriteLine("Name: {0}{1} D.O.B:{2} and Gender{3}", x.FirstName, x.Lastname, x.DOB, x.Gender);
}
}
else
{
Console.WriteLine(" Enter the correct information");
}
break;
case 2:
Console.WriteLine("You choose:2");
Console.WriteLine("Enter your Date of Birth in format MM/DD/YYYY:");
var b = DateTime.Parse(Console.ReadLine());
//Console.WriteLine(b);
//Console.ReadLine();
var case2 = students.Where(x => x.DOB == b);
temp=case2.Count(); //Getting result count in another variable
if (case2.Count() != 0)
{
Console.WriteLine("Found! Here are your details");
foreach (var x in case2)
{
Console.WriteLine("Name:{0} {1} DOB:{2} Gender:{3}", x.FirstName, x.Lastname, x.DOB, x.Gender);
}
}
else
{
Console.WriteLine(" Enter the correct information");
}
break;
default:
Console.WriteLine("Please enter the valid option");
break;
}
}while(temp==0); ////Endless Loop while result is zero
intially temp is equal to zero means result count is zero
so it will again intiate the loop However if there is any result
that means temp is not equal to zero it will not execute the code
Just use while loop.
Example from: https://www.dotnetperls.com/console-readline
using System;
class Program
{
static void Main()
{
while (true) // Loop indefinitely
{
Console.WriteLine("Enter input:"); // Prompt
string line = Console.ReadLine(); // Get string from user
if (line == "exit") // Check string
{
break;
}
Console.Write("You typed "); // Report output
Console.Write(line.Length);
Console.WriteLine(" character(s)");
}
}
}
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());
}
...
}
I am writing a program for shopping system. In this I am using array to get input from the brand name from the user. I am using method which returns string to get the input. Following is code:
public class Brand{
private string brandName;
public string BrandName
{
get { return brandName; }
set { brandName = value; }
}
public string getBrandName()
{
string[] brands = new string[5];
brands[0] = "Honda";
brands[1] = "Suzuki";
brands[2] = "Ferrari";
brands[3] = "BMW";
brands[4] = "Toyota";
Console.WriteLine("Please enter the brand name from the above given brands..");
string temp = Console.ReadLine();
do
{
try
{
for (int i = 0; i < 6; i++)
{
if (brands[i].Contains(temp))
{
this.BrandName = temp;
break;
}
}
return this.BrandName;
}
catch
{
Console.WriteLine("Your provide brand does not match with the database in our system. Please try another one.");
}
} while (BrandName!=temp);
}
}
The problem is that I am at beginner level and not getting the trick what should be in this while statement that it loops and asks user to input again and again until he enters the correct brand name. Please help me.
Maybe this will work based on your code:
public string getBrandName()
{
string[] brands = new string[5];
brands[0] = "Honda";
brands[1] = "Suzuki";
brands[2] = "Ferrari";
brands[3] = "BMW";
brands[4] = "Toyota";
Console.WriteLine("Please enter the brand name from the above given brands..");
string temp = Console.ReadLine();
while(!brand.Contains(temp))
{
Console.WriteLine("Your provide brand does not match with the database in our system. Please try another one.");
temp = Console.ReadLine();
}
return temp;
}
Few things to notice:
We will ask the user for a brand name.
We will check that the input is a brand from brands list (you use contains to check if the input is in the char array of every brand name, watch the difference).
If then name is in the list we will not enter inside the loop and we
will return the brand name.
If the name is not in the list we will ask the user again to insert a
valid brand name until he will enter any and then we will return it.
if you have only 4 no of brands then you can try or statement for all of them in while loop
while (input== 'brand1'||'brand2')
or if your list is too big then you can put them in an arraylist
like this
List <String> listClone = new ArrayList<String>();
for (String string : list) {
if(string.matches("(?i)(bea).*")){
listClone.add(string);
}
}
System.out.println(listClone);
You have an outOfRange exception here :
for (int i = 0; i < 6; i++)
beacuse there is out of range from the array where brands[5].
The function contains return true or false when the input string is substring of the specified string and not equel !!!
You arrive to this row only if has exception:
Console.WriteLine("Your provide brand does not match with the database in our system. Please try another one.");
Check the following code - it work well :
class Program
{
static void Main(string[] args)
{
Brand brand = new Brand();
string brandName = brand.getBrandName();
Console.WriteLine("You enter correct brand name !!!");
Console.WriteLine(brandName);
Console.ReadLine();
}
public class Brand
{
private string brandName;
public string BrandName
{
get { return brandName; }
set { brandName = value; }
}
public string getBrandName()
{
bool isValid = false;
string temp = "";
string[] brands = new string[5];
brands[0] = "Honda";
brands[1] = "Suzuki";
brands[2] = "Ferrari";
brands[3] = "BMW";
brands[4] = "Toyota";
Console.WriteLine("Please enter the brand name from the above given brands..");
while (!isValid)
{
for (int i = 0; i < brands.Length; i++)
{
Console.WriteLine(brands[i]);
}
temp = Console.ReadLine();
for (int i = 0; i < brands.Length; i++)
{
if (brands[i] == temp)
{
this.BrandName = temp;
isValid = true;
break;
}
else
{
isValid = false;
}
if (i == brands.Length - 1)
{
Console.WriteLine("Your provide brand does not match with the database in our system. Please try another one.");
}
}
}
return temp;
}
}
}
I have a generic list
How do I remove an item?
EX:
Class Student
{
private number;
public Number
{
get( return number;)
set( number = value;)
}
private name;
public Name
{
get( return name;)
set( name = value;)
}
main()
{
static List<student> = new list<student>();
list.remove...???
}
}
Well, there is nothing to remove because your list is empty (you also didn't give it an identifier, so your code won't compile). You can use the Remove(T item) or RemoveAt(int index) to remove an object or the object at a specified index respectively (once it actually contains something).
Contrived code sample:
void Main(...)
{
var list = new List<Student>();
Student s = new Student(...);
list.Add(s);
list.Remove(s); //removes 's' if it is in the list based on the result of the .Equals method
list.RemoveAt(0); //removes the item at index 0, use the first example if possible/appropriate
}
From your comments I conclude that you read student name from input and you need to remove student with given name.
class Student {
public string Name { get; set; }
public int Number { get; set; }
public Student (string name, int number)
{
Name = name;
Number = number;
}
}
var students = new List<Student> {
new Student ("Daniel", 10),
new Student ("Mike", 20),
new Student ("Ashley", 42)
};
var nameToRemove = Console.ReadLine ();
students.RemoveAll (s => s.Name == nameToRemove); // remove by condition
Note that this will remove all students with given name.
If you need to remove the first student found by name, first use First method to find him, and then call Remove for the instance:
var firstMatch = students.First (s => s.Name == nameToRemove);
students.Remove (firstMatch);
If you want to ensure there is only one student with given name before removing him, use Single in a similar fashion:
var onlyMatch = students.Single (s => s.Name == nameToRemove);
students.Remove (onlyMatch);
Note that Single call fails if there is not exactly one item matching the predicate.
List<Student> students = new List<Student>();
students.Add(new Student {StudentId = 1, StudentName = "Bob",});
students.RemoveAt(0); //Removes the 1st element, will crash if there are no entries
OR to remove a known Student.
//Find a Single Student in the List.
Student s = students.Where(s => s.StudentId == myStudentId).Single();
//Remove that student from the list.
students.Remove(s);
Well, you didn't give your list a name, and some of your syntax is wonky.
void main()
{
static List<Student> studentList = new List<Student>();
}
// later
void deleteFromStudents(Student studentToDelete)
{
studentList.Remove(studentToDelete);
}
There are more remove functions detailed here: C# List Remove Methods
int count=queue.Count;
while(count>0)
{
HttpQueueItem item = queue[0];
/// If post succeeded..
if (snd.IsNotExceedsAcceptedLeadsPerDayLimit(item.DataSaleID, item.AcceptedLeadsPerDayLimit) && snd.PostRecord(item.DataSaleDetailID, item.PostString, item.duplicateCheckHours, item.Username, item.Password, item.successRegex))
{
if (item.WaitTime > 0)
Thread.Sleep(item.WaitTime);
queue.Remove(item);
}
///If Exceeds Accepted leads per day limit by DataSale..
else if (!snd.IsNotExceedsAcceptedLeadsPerDayLimit(item.DataSaleID, item.AcceptedLeadsPerDayLimit))
{
queue.RemoveAll(obj => obj.DataSaleID == item.DataSaleID);
}
/// If Post failed..
else //if (!snd.PostRecord(item.DataSaleDetailID, item.PostString, item.duplicateCheckHours, item.Username, item.Password, item.successRegex))
{
queue.Remove(item);
}
count = queue.Count;
}
To delete a row or record from generic list in grid view, just write this code-
List<Address> people = new List<Address>();
Address t = new Address();
people.RemoveAt(e.RowIndex);
grdShow.EditIndex = -1;
grdShow.DataSource = people;
grdShow.DataBind();
Maybe you can use a Dictionary<string, Student> instead of the List<Student>.
When you add a Student, add its ID or Name or whatever can uniquely identify it. Then you can simply call myStudents.Remove(myStudentId)
Try linq:
var _resultList = list.Where(a=>a.Name != nameToRemove).Select(a=>a);
I made a program that contains 7 cards, then shuffle and I hope to take in order to help them
class Program
{
static void Main(string[] args)
{
Random random = new Random();
var cards = new List<string>();
//CARDS VECRTOR
String[] listas = new String[] { "Card 1", "Card 2", "Card 3", "Card 4", "Card 5", "Card 6", "Card 7"};
for (int i = 0; i<= cards.Count; i++)
{
int number = random.Next(0, 7); //Random number 0--->7
for (int j = 0; j <=6; j++)
{
if (cards.Contains(listas[number])) // NO REPEAT SHUFFLE
{
number = random.Next(0, 7); //AGAIN RANDOM
}
else
{
cards.Add(listas[number]); //ADD CARD
}
}
}
Console.WriteLine(" LIST CARDS");
foreach (var card in cards)
{
Console.Write(card + " ,");
}
Console.WriteLine("Total Cards: "+cards.Count);
//REMOVE
for (int k = 0; k <=6; k++)
{
// salmons.RemoveAt(k);
Console.WriteLine("I take the card: "+cards.ElementAt(k));
cards.RemoveAt(k); //REMOVE CARD
cards.Insert(k,"Card Taken"); //REPLACE INDEX
foreach (var card in cards)
{
Console.Write(card + " " + "\n");
}
}
Console.Read(); //just pause
}
}