How to Create An Array From User Input - c#

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

Related

C# How can I change the value from static class?

So this is the Program cs. I want to change the value of int in my StaticClass.cs ** I want to delcare a printing sentence " How long do you want me to generate " then change the value of N in StaticClass.
class Program
{
static void Main(string[] args)
{
Constructor ct = new Constructor(StaticClass.n);
//ct.xmethod(StaticClass.n);
Console.ReadKey();
}
}
Here my constructor class. Method of Pascal Triangle
class Constructor
{
int[][] triangle = new int[StaticClass.n][];
public Constructor(int n)
{
xmethod(n);
}
public void xmethod(int n)
{
for (int row = 0; row < triangle.Length; row++)
{
//Each row is a subarray of length 1 greater than row number
triangle[row] = new int[row + 1];
//set the values in a row
for (int k = 0; k < triangle[row].Length; k++)
{
// if not first or last element in the row
if (k > 0 & k < triangle[row].Length - 1)
//set it to sum of the element above it
//and the one above and to the left
triangle[row][k] = triangle[row - 1][k - 1] + triangle[row - 1][k];
//otherwise this is an end point, set it to 1
else
triangle[row][k] = 1;
//display value
Console.Write(triangle[row][k] + "\t");
}
// Finished processing row-send cursor to next line
Console.WriteLine();
}
}
}
Here my StaticClass for the long of Pascal Triangle
class StaticClass
{
public const int n = 15;
// I want to change the value of N using the Console Writeline.
}
n needs to be updatable then instead of const use static; but Console.WriteLine() is not something you would use to change the value. You'll need to be more clear about what you want to do. Do you want someone to input the value of n - with a Console.ReadLine?
So ... from what I gather -- I think you want to change your Main to write your question: " How long do you want me to generate " then read the line for user input. Then print your triangle. Something like :
static void Main(string[] args)
{
Console.WriteLine("How long do you want me to generate? ");
int inNum = int.Parse(Console.ReadLine());
Constructor ct = new Constructor(inNum);
Console.ReadKey();
}
Then from what I see ... your Constructor needs to change:
public Constructor(int n)
{
triangle = new int[n][];
xmethod(n);
}
You cannot change the value of a const. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/constants
Use a static property instead.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members
static class StaticClass
{
public static int n = 15;
// I want to change the value of N using the Console Writeline.
}
Make your public const field a public static property instead:
public static int N { get; set; } = 15;
Change it like
StaticClass.N = 16;
You said "change it with WriteLine" - WriteLine outputs things, it doesn't change thing. Perhaps you meant ReadLine:
Console.WriteLine("How many levels? ");
string input = Console.ReadLine();
StaticClass.N = int.Parse(input);
Do please find a better name for StaticClass; classes should be named for what they represent in a more real world sense (like.. Configuration?) not what they are in a C# sense (yes, it's a static class, but it doesn't mean we should call it that)

Creating new class instance in a loop

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

C# Populate object array with user input

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.

Using Method and passing values to main method

So I have a question that ask for a Movies method, to accept a name as string and a integer(represents time in minutes). So if you call this method without an integer minutes is set to a default of 90. Then the main method shows that you can call the movies method with only a string as well show you can call it with a string and integer.
static void Main()
{
Console.WriteLine("Movie title is {0}, and time is", MovieListing("x") );
}
private static string MovieListing(string name, int defaultTime = 60)
{
string Name, stringTime;
int time;
bool isValid;
Console.Write("What is the name of the movie?");
Name = Console.ReadLine();
Console.Write("What is the time of the movie? Default is 90 if left blank");
stringTime = Console.ReadLine();
time = Convert.ToInt32(stringTime);
}
So Im left blank thinking how to get the program to tell if the user entered a time int and use that or if they are just using the default 90 and passing them back to the main method sorry if the codes a mess was trying different ways without much success
You can use the ternary operation to check if the entered value is empty:
time = string.IsNullOrEmpty(stringTime) ? defaultTime : Convert.ToInt32(stringTime);
It will parse the stringTime if filled, else it will take the default.
Here's a better way to do this, using a simple Movie object to hold the values. This should print out two hardcoded lines to demo and then ask the user for input:
private class Movie
{
private readonly int _defaultLength = 90;
public string Title { get; set; }
public int Length { get; set; }
// constructor without length - use default length
public Movie(string title)
{
this.Title = title;
this.Length = _defaultLength;
}
// constructor with both properties
public Movie(string title, int length)
{
this.Title = title;
// make sure Length is valid
if (length > 0)
this.Length =length;
else
this.Length = _defaultLength;
}
}
static void Main()
{
// make a Movie object without length
var shortMovie = new Movie("Zombieland");
// make a Movie object and specify length
var longMovie = new Movie("Lawrence of Arabia", 216);
Console.WriteLine("{0} is {1} minutes long", shortMovie.Title, shortMovie.Length);
Console.WriteLine("{0} is {1} minutes long", longMovie.Title, longMovie.Length);
// get input from user: title
Console.Write("What is the name of another movie?");
var userTitle = Console.ReadLine();
// get input from user: length
Console.Write("What is the length of {0}? Default is 90 if left blank", userTitle);
var userTime = Console.ReadLine();
// try to convert user input to an int and call Movie constructor to create a new object
int userTimeConverted = 0;
Movie userMovie;
if (Int32.TryParse(userTime, out userTimeConverted))
{
// make a new Movie object with the user's input
userMovie = new Movie(userTitle, userTimeConverted);
}
else
{
// make a new Movie object without the user's input
userMovie = new Movie(userTitle);
}
Console.WriteLine("{0} is {1} minutes long", longMovie.Title, longMovie.Length);
}
By building a separate Movie object, we can move most or all of the logic needed for storing a default length and checking to see if the length is valid out of the Main() method. This should hopefully be much cleaner and easier to read.
As an added bonus, we can create as many instances of Movie as we want - as demonstrated in the above code.
Set the default value to something you wouldnt expect the user to enter and detect and handle that.
private static string MovieListing(string name, int defaultTime = -1)
{
var isDefaultUsed = false;
if (defaultTime = -1)
{
isDefaultUsed = true;
defaultTime = 60;
}
string Name, stringTime;
int time;
bool isValid;
Console.Write("What is the name of the movie?");
Name = Console.ReadLine();
Console.Write("What is the time of the movie? Default is 90 if left blank");
stringTime = Console.ReadLine();
time = Convert.ToInt32(stringTime);
}

Difficulty with passing arrays and manipulating data in arrays (Homework) c#

So I am doing a Homework assignment for c#. The assignment requires the use of 2 arrays, one to hold names and the other to hold scores. We are then to calculate the average score, display the below average scores, and display the scores according to name. I am having a significant amount of difficulty passing the arrays by reference/value in order to use the data in them and maintain my code using separate modules. The arrays have to hold up to 100 individual pieces of data.
class Program
{
static void Main(string[] args)
{
string[] playerNames = new string[100];
int[] playerScores = new int [100];
int numPlayers = 0;
double averageScore;
DisplayData(playerNames);
}
static void InputData(string[] playerNames, int[] playerScores, ref int numPlayers)
{
string playerName;
do
{
int i = 0;
Console.WriteLine("Enter the name of the player...Enter \"Q to exit...");
playerName = Console.ReadLine();
if (playerName == "Q" || playerName == "q")
Console.WriteLine("No further user input needed...\n");
else
playerNames[i] = playerName;
Console.WriteLine("Enter the score of the player...");
int playerScore = Convert.ToInt32(Console.ReadLine());
playerScores[i] = playerScore;
numPlayers += i;
i++;
}
while (playerName != "Q");
}
static void CalculateAverageScore(int[] playerScores, ref int averageScore)
{
InputData(playerScores);
InputData(ref numPlayers);
int averageScores = 0;
averageScores = playerScores / numPlayers;
}
The biggest question I have is that I cannot seem to pass the array data. I am plagued by "No overload method for "Input Data" or whatever method I am using. So I'm curious as to how I can pass the array data to another method.
Since this is homework, I won't give you the full answer, but here is a way forward.
Instead of using the ref keyword, just pass the array into the method. Have the method return an int instead of void. Calculate the average within the method and have the final line of the method return the int that you've calculated
static int CalculateAverageScore(int[] playerScores)
{
// calculate average
return average; // the int you've calculated.
}
Call the method from the main, when you need to acquire the average.
Also, are you missing some braces { } for the 6 lines that come after your else statement?

Categories

Resources