I'm new to c# and having a hard time figuring out how to populate an array from user input. I have an array of 5 job objects
static Job[] jobArray = new Job[5];
The user will be inputting a description for each job, time to complete each job and the pay for each job. I need to put those inputted values into the array.
Any help would be appreciated, thanks.
Basically what you need to keep in mind is that the row above where you initialize an array does not create the objects within it but only the array.
For each position of the array you need to request the information from the user and store it in the proper property. Then you assign that new object to the array.
This code sample does it for the Description, Hours and Pay properties of Job
Job[] jobArray = new Job[5];
for (int i = 0; i < jobArray.Length; i++)
{
Job job = new Job();
Console.WriteLine("Job " + i);
Console.WriteLine("Enter description:");
job.Desciption = Console.ReadLine();
Console.WriteLine("Enter hours:");
job.Hours = Console.ReadLine();
Console.WriteLine("Enter pay:");
job.Pay = Console.ReadLine();
jobArray[i] = job;
}
Make a function to read a Job:
static Job ReadJob() {
return new Job() {
Name = Console.ReadLine(),
Description = Console.ReadLine(),
//...
};
}
And then fill the array:
for (int i = 0; i < jobs.Length; i++)
jobs[i] = ReadJob();
Endless variants of this are possible.
Related
I've just started learning about methods and classes, I would like to know if I can have something like,
CarsSold Day1 = new CarsSold();
in a for loop where it will create a new instance of a new day each time it runs. For example on the second time the loop runs I want it to create an instance like this,
CarsSold Day2 = new CarsSold();
I have tried to use an array but either it cant be done with arrays or I'm using the wrong syntax. Thanks in advance.
Full code
class Program
{
static void Main(string[] args)
{
int[] weekDay = new int[7];
int userInput;
int x;
for (x = 0; x < weekDay.Length; x++)
{
Console.Write("Enter the number of cars sold: ");
bool ifInt = int.TryParse(Console.ReadLine(), out userInput);
CarsSold Day[x] = new CarsSold(userInput);
}
}
}
The problem is how you're trying to define your array. The syntax is invalid, and you're doing it in the wrong place.
You should define the array before your loop, and then only assign values to the array within the loop.
static void Main(string[] args)
{
int userInput;
CarsSold[] days = new CarsSold[7]; // create an array with 7 items
int x;
for (x = 0; x < days.Length; x++)
{
Console.Write("Enter the number of cars sold: ");
bool ifInt = int.TryParse(Console.ReadLine(), out userInput);
days[x] = new CarsSold(userInput); // assign a value to the days array at position x.
}
}
Note also that arrays start from 0, not 1, so the first item is actually days[0], and the last is days[6] (for a 7-item array). I took the liberty of removing weekDays since it wasn't needed here, and replaced it in the loop with days.Length.
Arrays can have set amount of things in them, so if you declare an array like this
object[] objectArray = new object[10];
Then that array can hold only 10 objects. If you want to add anything to an array you have to chose an index to which that thing will be assigned to, for example:
objectArray[2] = "some value";
in Your case you could iterate through the array and add new object to each index like this
for (var i = 0; i < objectArray.Length; i++)
{
objectArray[i] = new YourObject();
}
If the amount of objects you want to store is unknown and can change then you should use collections, for example a List
List<object> listOfObjects = new List<object>();
Now if you want to add anything to that list you simply do
listOfObjects.Add(itemYouWantToAddToTheList);
You access lists the same way you would access arrays, so you can use indexes like
var someValue = listOfObjects[0];
As you probably noticed this list has a generic parameter <object>, it tells the list what type of data it can store, in my example its the object type so it can pretty much store anything, but you can set it to string or int or any other type like your own class types and then this list would store only those types of objects.
If you don't know the number of days, then:
IList<CarsSold> soldCarsList = new List<CarsSold>();
foreach(var day in Days)
{
soldCarsList.Add(new CarsSold());
}
If you know the number of days(e.g:7), then:
CarsSold[] soldCarsArray = new CarsSold[7];
for (int i = 0; i < days.Length; x++)
{
soldCarsArray[i] = new CarsSold();
}
I am working on an assignment for school (Assignment Here).
I am currently trying to shuffle a deck of cards. I have used PlayingCards from Codeplex (sorry, could only have two links...) to create a collection of cards to create a deck. Please help, when I click the Shuffle button, nothing happens. You can see my progress here it's easier to see the entire code: Github
public void Shuffle()
{
PlayingCards.Deck theDeck = new PlayingCards.Deck();
random = new Random();
for (int i = 0; i < theDeck.Cards.Count; i++)
{
int second = random.Next(NUMBER_OF_CARDS);
PlayingCards.Card temp = theDeck.Cards[i];
theDeck.Cards[i] = theDeck.Cards[second];
theDeck.Cards[second] = temp;
}
}
You are creating a new instance of PlayingCards.Deck, shuffling it, and then throwing it away at the end of the shuffle.
PlayingCards.Deck theDeck = new PlayingCards.Deck();
You need to change the call to Shuffle to include PlayingCards.Deck as a parameter, so you should be doing this:
public void Shuffle(PlayingCards.Deck theDeck)
{
random = new Random();
for (int i = 0; i < theDeck.Cards.Count; i++)
{
int second = random.Next(NUMBER_OF_CARDS);
PlayingCards.Card
temp = theDeck.Cards[i];
theDeck.Cards[i] = theDeck.Cards[second];
theDeck.Cards[second] = temp;
}
}
You should also move the new Random() outside of this method as you may find that if you tried to create two shuffled decks immediately after one another that they'll have the same order because the seed Random uses is based on the system clock.
I had a look at the code you've got for adding the cards to the deck. You should use this code instead:
foreach (var face in Enum.GetValues(typeof(PlayingCards.CardSuits)).Cast<PlayingCards.CardSuits>())
{
foreach (var value in Enum.GetValues(typeof(PlayingCards.CardValues)).Cast<PlayingCards.CardValues>())
{
theDeck.Cards.Add(new PlayingCards.Card(face, value));
}
}
I have a button event in which generates some random numbers based upon the number typed into a textbox (for example, if I type 5, it should generate 5 different random numbers). When I type in a number into the textbox, and click the btnGenerateScores button, it generates a single number and puts that number in the listbox 5 times (or however many times based upon the number in the textbox). This behavior is not correct, it should generate 5 different numbers and list each in the listbox. If I put a MessageBox.Show (I was using it for debugging) command anywhere in the code block, it works correctly. Commenting out the MessageBox.show breaks the code. Does anyone see any reason why it would not work correctly when I don't show the message box? The code is below:
private void btnGenerateScores_Click(object sender, EventArgs e)
{
strInput = txtInputNumber.Text;
intRandCount = Convert.ToInt16(strInput);
scoresArray = new int[intRandCount];
intArrayCount = scoresArray.Length;
btnGenerateScores.Enabled = false;
// Loop to generate random number
for (intRndCount = 0; intRndCount < intRandCount; intRndCount++)
{
GetRand(intRandCount);
scoresArray[intCount] = intRandomNum;
intGenRandom = intRandomNum;
intArrScores = scoresArray[intCount];
lstRdmScores.Items.Add(Convert.ToString(intArrScores));
insertionSortArray = new int[intArrayCount];
Array.Copy(scoresArray, insertionSortArray, intArrayCount);
// Instantiate an instance of the class
arraySort mySort = new arraySort();
// Get the number of elements to store in the array
string s = Convert.ToString(intCount);
mySort.x = Int16.Parse(s);
// Get array elements
for (int i = 0; i < mySort.x; i++)
{
intInsertionSort = insertionSortArray[intCount];
string s1 = Convert.ToString(intInsertionSort);
mySort.a[i] = Int16.Parse(s1);
}
// Sort the array and display in the second list box
mySort.sortArray();
intSortScores = insertionSortArray[intCount];
lstSortScores.Items.Add(Convert.ToString(intSortScores));
// This is the the MessageBox.Show command in question:
MessageBox.Show("The random number generated is: "); //+ Convert.ToString(intGenRandom));
}
}
ignore the fact that the array does not sort correctly, I will get to that later. I want to work on one thing at a time.
I am using VS 2013 and the code was originally created in VS 2005.
As your requirement, and view the source, I rewrite the app for short:
private void btnGenerateScores_Click_1(object sender, EventArgs e)
{
int genTimes;
if (Int32.TryParse(txtInputNumber.Text, out genTimes))
{
var ints = new List<int>();
for (var i = 0; i < genTimes; i++)
{
var r = new Random(Guid.NewGuid().GetHashCode());
var rInt = r.Next(0, int.MaxValue); //for ints
ints.Add(rInt);
}
var copyInts = ints.ToList();
copyInts.AddRange(this.listBox1.Items.Cast<int>());
copyInts = copyInts.Distinct().OrderBy(x => x).ToList();
this.listBox1.Items.Clear();
this.listBox1.Items.AddRange(copyInts.Cast<object>().ToArray());
MessageBox.Show("The random number generated is: " + String.Join(",", ints));
}
}
}
Hope this help.
public class TEST
{
static void Main(string[] args)
{
string Name = "";
double Value = 0;
Array test1 = new Array(Name, Value);
for (int i = 0; i < 2; i++)
{
Console.WriteLine("Enter A Customer:");
Name = Console.ReadLine();
Console.WriteLine("Enter {0} Insurance Value (numbers only):", Name);
Value = Convert.ToDouble(Console.ReadLine());
}
test1.Display();
Console.ReadLine();
}
}
So in another class, I have my arrays. The way it is set up, it adds one user at a time to the arrays and adds that users corresponding number in another array.
The part I am having problems with is the main coding. I prompt the user for input and want it to call my other class method and fill the array up one user at a time. BUT, I am stuck.
I know why the code above isn't working, because the object call is only called once and so the initial value is the one that is saved. But when I put the new Array(Name, Value); in the for loop it tells me that test1.Display(); is an unassigned variable.
Is there a way I can solve this. I know there is probably another easier way using list or something, but I haven't gotten that far yet. If you could explain or hint or anything, I'd appreciate it. :)
It is better in this situation to use List<T>.
You have to create a class and after that you can create a List<T> to save items:
public class Customer
{
public string Name {get;set;}
public double Value {get;set;}
}
and :
static void Main(string[] args)
{
List<Customer> customers = new List<Customer>;
for (int i = 0; i < 2; i++)
{
Console.WriteLine("Enter A Customer:");
Customer customer = new Customer(); // create new object
customer.Name = Console.ReadLine(); // set name Property
Console.WriteLine("Enter {0} Insurance Value (numbers only):", Name);
customer.Value = Convert.ToDouble(Console.ReadLine());// set Value Property
customers.Add(customer); // add customer to List
}
Console.ReadLine();
}
So for my homework assignment I need to write a type of program that has the user type in the persons name and then their score. It then needs to find the highest, lowest, and the average score and list the player that achieved each one.
static void Main()
{
string userInput;
Console.Write("Please enter bowler's first name and then a score then use a comma to seperate plays\nExample: Elliott 200,John 180,Jane 193\nPlease enter values here: ");
userInput = Console.ReadLine();
char[] delimiters = new char[] { ' ', ','};
string[] parts = userInput.Split(delimiters);
for (int i = 0; i < parts.Length; i++)
{
Console.WriteLine(parts[i]);
}
Console.ReadLine();
}//End Main()
As you can see I've figured out how to split the input, but I don't know how to organize them and pair them together. I've been looking online for an answer and have heard of lists but I've never used them. It this even possible on an array? Do I need to do this on two different arrays?
I have also tried splitting into two arrays but it has a convert issue
string userInput;
const int ZERO = 0;
const int ONE = 1;
const int TEN = 10;
string[] parsedInput = new string[TEN];
string[] name = new string[TEN];
int[] score = new int[TEN];
for (int i = 0; i < TEN; ++i)
{
Console.Write("Please enter bowler's first name and then a score\nExample: Name 200\nPlease enter values here: ", i);
userInput = Console.ReadLine();
parsedInput = userInput.Split();
name = parsedInput[ZERO];
score = int.Parse(parsedInput[ONE]);
}
When you say you don't know how to pair them together, this is what a class is for.
public class Person
{
public string Name { get; set; }
public int Score { get; set; }
}
Once you have that, you're on the right track with using a List instead of an array (not that you couldn't use arrays but this would be the preferred way)
List<Person> people = new List<Person>();
You can then use a loop to go through your list and access the properties.
foreach(Person person in people)
{
Console.WriteLine(person.Name + ", " + person.Score.ToString());
}
The other answer posted is fine, but you should probably focus on something like this first if you are just learning.
You definitely can do that using simple array of string. But I'm not going to give you code like that. You should definitely spend much more time to learn about classes, arrays, lists, loops, etc. You're not gonna learn anything unless you do it by yourself.
And just to show you, how it could be done when you know the language you're using well: LINQ one-liner to get a list of anonymous type objects, sorted descending by the value:
var items = input.Split(',')
.Select(x => x.Split(' '))
.Select(x => new { name = x[0], value = int.Parse(x[1]) })
.OrderByDescending(x => x.value)
.ToList();
And taking what you need from the list:
// min/max are items, so both .name and .value are there
var maxItem = items.First();
var minItem = items.Last();
// average is just a number
var average = items.Average(x => (double)x.value);