namespace ConsoleApplication13
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("how many footballs would you want?");
int amount = int.Parse(Console.ReadLine());
List<football> ballist = new List<football>();
for (int i = 0; i < amount; i++)
{
Console.WriteLine("how much should football {0} weigh?", i+1);
int weight = int.Parse(Console.ReadLine());
ballist.Add(new football(weight));
}
Console.WriteLine("amount of footballs is {0}", amount);
ballist.ForEach(s => Console.WriteLine(s.GetWeight()));
Console.ReadLine();
}
}
class football
{
private int weight = 0;
public int GetWeight()
{
return weight;
}
public football(int weigh)
{
weight = weigh;
}
}
}
adding objects in a list, am i doing it right?
A possible alternative is to let user input all the weights in one go and generate the list:
Console.WriteLine("please, input footballs' weights separated by comma");
String input = Console.ReadLine();
List<football> ballist = input
.Split(',')
.Select(item => new football(int.Parse(item)))
.ToList();
Some suggestions on Football class
// We usually start classes with capital letter
class Football {
private int m_Weight;
// C# is not Java, so use properties, which are more readable
public int Weight {
get {
return m_Weight;
}
private set {
// validate input
if (value <= 0)
throw new ArgumentOutOfRangeException("value");
m_Weight = value;
}
}
// "weight" - let argument correspond to property
public football(int weight) {
Weight = weight;
}
}
The adding to the list is right. I would recomend you to use property for the Weight.
class football
{
public int weight { get; set; }
}
If you dont want to have any code on the get/set.
public int _weight;
public int weight
{
get
{
//Your Code here
return _weight;
}
set
{
//And Here
_weight = value;
}
}
Related
I was expected that constructor can go into the setter condition, I have done the following attempts.
static void Main(string[] args)
{
Iitem car = new Car(7000);
Console.WriteLine($"cost={car.cost}");//expect output "too expensive",but actually show 7000
car.cost = 7000;
Console.ReadLine();
}
public interface Iitem
{
int cost { get; set; }
string status {get;set; }
}
class Car:Iitem
{
private int mycost;
public int cost
{
get { return mycost; }
set
{
if (value > 5000)
{
mycost = 0;
Console.WriteLine("too expensive");
}
else
{
mycost = value;
}
}
}
public string status { get; set; }
public Car(int cost)
{
this.mycost = cost;
}
}
If I discard car.cost=7000 from Main() function, then I can't get the output of too expensive.
you are not getting the desired result because you are setting the value directly into the variable "mycost" in the constructor. Replace it with this.cost = cost;
I want to create an array of class type elements.
And it would be nice to enter this data from the keyboard, but I don’t know yet how, any Tips?
class Transportation
{
private string name; //name company
private double cost; //unit price
private double weight; // Shipping Weight
public Transportation(string name,double cost, double weight)
{
Name = name;
Cost = cost;
Weight = weight;
}
public Transportation()
{
Name = "none";
Cost = 0;
Weight = 0;
}
public double Cost { get => cost; set => cost = value; }
public string Name { get => name; set => name = value; }
public double Weight { get => weight; set => weight = value; }
}
class Program
{
static void Main(string[] args)
{
Transportation company = new Transportation("LG",24.05,1000);
}
}
Yuriy, sorry by my english.
If I understand correctly, you want to create an array of a class, in this case the Transportation class
This do the magic
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Transportation
{
private string name; //name company
private double cost; //unit price
private double weight; // Shipping Weight
public Transportation(string name, double cost, double weight)
{
Name = name;
Cost = cost;
Weight = weight;
}
public Transportation()
{
Name = "none";
Cost = 0;
Weight = 0;
}
public double Cost { get => cost; set => cost = value; }
public string Name { get => name; set => name = value; }
public double Weight { get => weight; set => weight = value; }
}
class Program
{
static void Main(string[] args)
{
Transportation[] company = GetTransportations();
foreach (Transportation item in company)
{
Console.WriteLine(item.Name + " => " + item.Cost + " => " + item.Weight);
}
Console.ReadKey();
}
public static Transportation[] GetTransportations()
{
string name = string.Empty; //name company
double cost = 0; //unit price
double weight = 0; // Shipping Weight
Transportation[] transportations = new Transportation[] { };
List<Transportation> transportationsList = new List<Transportation>();
while (true)
{
while (true)
{
Console.WriteLine("Insert the name of product: ");
name = Console.ReadLine();
if (!string.IsNullOrEmpty(name))
{
break;
}
}
while (true)
{
Console.WriteLine("Insert the cost of product: ");
string costString = Console.ReadLine();
if (double.TryParse(costString, out double c))
{
cost = c;
break;
}
}
while (true)
{
Console.WriteLine("Insert the weight of product: ");
string Sweight = Console.ReadLine();
if (double.TryParse(Sweight, out double w))
{
weight = w;
break;
}
}
transportationsList.Add(new Transportation(name, cost, weight));
Console.WriteLine("Continue to add products? Y/N: ");
string continueToAdd = Console.ReadLine();
if (continueToAdd.Substring(0, 1).ToUpper() == "N")
{
return transportationsList.ToArray();
}
}
}
}
}
This is homework, but a small portion...
I'm trying to return the largest number in an array using arr.MAX(); , but I keep on getting zero.
After debugging, I can see that values are being stored (from the user) yet it still returns zero.
The method in question is at the bottom.
Class ElectionUI
{
public void candidateInfo()
{
do
{
for (int i = 0; i < theElection.CandidateNames.Length; i++)
{
Console.Write("Please enter the name for Candidate #" + (i +
1) + ": ");
theElection.CandidateNames[i] = Console.ReadLine();
Console.Write("Please enter the number of votes for: {0}: ",
theElection.CandidateNames[i]);
theElection.NumVotes[i] = int.Parse(Console.ReadLine());
Console.WriteLine("");
}
} while (theElection.NumVotes.Length < 5);
}
}
Class Election
{
private string[] candidateNames = new string[5];
private int[] numVotes = new int[5];
//get/set Candidate Names
public string[] CandidateNames
{
get { return candidateNames; }
set { candidateNames = value; }
}
//Get/Set Candidate votes
public int[] NumVotes
{
get { return numVotes; }
set { numVotes = value; }
}
public void findWinner()
{
int max = NumVotes.Max();
for (var i = 0; i < numVotes.Length; i++)
{
if (NumVotes[i] > max)
{
max = NumVotes[i];
}
}
Console.WriteLine(max);
}
}
from the code its not clear, how you are initializing you election class instance, and how you are calling findWinner method. And yes your Do-While looping doing nothing. Because you already set the name array length as 5 so it will run the for loop once and then it will exit. even if you remove your do-while you will get the same output.
check the fiddle your code is working fine. I just assume you are creating instance of Election and then passing it to ElectionUI class to use it.
https://dotnetfiddle.net/oiVK9g
using System;
using System.Linq;
public class Program
{
public static void Main()
{
var ele = new Election();
var ui = new ElectionUI(ele);
ui.candidateInfo();
ele.findWinner();
}
}
class ElectionUI
{
Election theElection;
public ElectionUI(Election obj)
{
theElection = obj;
}
public void candidateInfo()
{
do
{
for (int i = 0; i < theElection.CandidateNames.Length; i++)
{
Console.Write("Please enter the name for Candidate #" + (i +
1) + ": ");
theElection.CandidateNames[i] = Console.ReadLine();
Console.Write("Please enter the number of votes for: {0}: ",
theElection.CandidateNames[i]);
theElection.NumVotes[i] = int.Parse(Console.ReadLine());
Console.WriteLine("");
}
} while (theElection.NumVotes.Length < 5);
}
}
class Election
{
private string[] candidateNames = new string[5];
private int[] numVotes = new int[5];
//get/set Candidate Names
public string[] CandidateNames
{
get { return candidateNames; }
set { candidateNames = value; }
}
//Get/Set Candidate votes
public int[] NumVotes
{
get { return numVotes; }
set { numVotes = value; }
}
public void findWinner()
{
int max = NumVotes.Max();
Console.WriteLine(max);
}
}
I think that you wanted to return the candidate name of who won, right?
Using your code you should change the findWinner method to:
public void findWinner()
{
int max = NumVotes.Max();
string winnerName = null;
for (var i = 0; i < numVotes.Length; i++) {
if (NumVotes[i] = max) {
winnerName = CandidateNames[i];
}
}
Console.WriteLine(winnerName);
}
You need to initialize the local variable max with Int32.MinValue. That way any value encountered will replace it.
So i'm currently trying to calculate the sum of all bags in the array using a recursive method. I'm sure it's easy, but I can't seem to get my head around it. Any assistance would be appreciated! - Cheers.
class Program
{
static void Main(string[] args)
{
List<Bag> bags = new List<Bag>();
bags.Add(new Bag("Blue", 25));
bags.Add(new Bag("Red", 35));
bags.Add(new Bag("White", 30));
int totalVolume = CalcTotalVolume(bags);
Console.WriteLine("Total volume of bags: {0}", totalVolume);
}
static int CalcTotalVolume(List<Bag> bagList)
{
//resursive method
//1. base case is when the list is empty
if (bagList.Count == 0)
{
return 0;
}
else
{
List<int> subList = bagList.GetRange(1, bagList.Volume - 1);
int subTotal = CalcTotalVolume(subList);
int total = bagList[1] + subTotal;
return total;
}
}
}//end of class Program
class Bag
{
public string Colour { get; set; }
public int Volume { get; set; }
public Bag(string co, int vo)
{
Colour = co;
Volume = vo;
}
}
Obviously a loop is a lot more efficient, but just for a kata, this is sort of interesting...
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Bag> bags = new List<Bag>();
bags.Add(new Bag("Blue", 25));
bags.Add(new Bag("Red", 35));
bags.Add(new Bag("White", 30));
int totalVolume = CalcTotalVolume(bags);
Console.WriteLine("Total volume of bags: {0}", totalVolume);
Console.ReadKey(true);
}
static int CalcTotalVolume(IEnumerable<Bag> bags)
{
//resursive method
//1. base case is when the list is empty
var bag = bags.FirstOrDefault();
if (bag == null) return 0;
var subList = bags.Skip(1);
return bag.Volume + CalcTotalVolume(subList);
}
}
class Bag
{
public string Colour { get; set; }
public int Volume { get; set; }
public Bag(string co, int vo)
{
Colour = co;
Volume = vo;
}
}
}
It would be interesting to know what kind of recursion you want. For example, the following also uses a recursive method but it amounts to a simple summing loop:
class Bag
{
public string Colour { get; }
public int Volume { get; }
public Bag(string c, int v)
{
Colour = c;
Volume = v;
}
}
class Program
{
static int CalcTotalVolumeIdx(List<Bag> bags, int i, int sum)
{
return (i >= bags.Count) ? sum :
CalcTotalVolumeIdx(bags, i + 1, sum + bags[i].Volume);
}
static int CalcTotalVolume(List<Bag> bags)
{
return CalcTotalVolumeIdx(bags, 0, 0);
}
static void Main(string[] args)
{
List<Bag> bags = new List<Bag>();
bags.Add(new Bag("Blue", 25));
bags.Add(new Bag("Red", 35));
bags.Add(new Bag("White", 30));
int totalVolume = CalcTotalVolume(bags);
Console.WriteLine("Total volume of bags: {0}", totalVolume);
}
}
As a side note, F# would actually compile the function CalcTotalVolumeIdx() into a while loop since this type of recursion is a well-known pattern that can be efficiently converted.
Edited to reflect Brian's comment. Thank you!
I am trying to store user-provided values in order to calculate their sum and average for an assignment. I am able to print the values, but not store them.
I am not looking for the answer, but only for guidance.
Thank you for any and all responses.
public class average {
public int num;
public double avg;
public average() { } // no argument method
public average(int nums, double avgt) {
num = nums;
avg = avgt;
}
public int Num {
get { return num; } // used to get the contents from the main()
set { num = value; }
}
public double Avg {
get { return avg; }
set { avg = value; }
}
public void print_info() { // prints the final results of code
// Cannot get the values to store properly
Console.WriteLine("The average is {0}, the sum of 10 numbers is {1}", (avg/10),num);
Console.WriteLine("Press any key to continue . . .");
Console.ReadLine();
}
{class assignment1 // wrapper class for main
static void Main(string[] args) {
int num0;
int val;
int nums = 0;
double avgt = 0.0;
average num1 = new average(nums, avgt);
for (val = 0; val < 10; val++) { // loop for user input
Console.Write("Enter an integer value: ");
num0 = Convert.ToInt32(Console.ReadLine());
}
num1.print_info(); // calls print_info() method
}
}
}