Storing user-provided values - c#

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
}
}
}

Related

Array not returning max value

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.

Difficulty returning some values in C#

So I'm going to simplify an assignment I'm working on. I'm sorry if it's crazy bad I'm very new to C#. I should add that the finalMethod call is within Main() and is the only thing in Main().
finalMethod(ifPossible(functionOne()), functionTwo()))
static int functionOne()
{
int number;
Console.WriteLine("Enter a number: ");
number = int.Parse(Console.ReadLine());
return number;
}
static int functionTwo()
{
int number;
Console.WriteLine("Enter a number: ");
number = int.Parse(Console.ReadLine());
return number;
}
static bool ifPossible(int x, int y)
{
if (x < y)
{
return true;
}
else
{
return false;
}
}
static int finalMethod(bool x)
{
if (x == true)
{
Console.Write("Success");
}
else
{
Console.Write("Fail");
}
}
My problem is that I need to return the int values from the first two functions into the finalMethod function. This is probably going to require a lot of restructuring but any help would be greatly appreciated.
You have a close ) on a wrong place. Try this:
finalMethod(ifPossible(functionOne(), functionTwo()));
Try to do some refactoring like this:
static int getInputValue()
{
Console.WriteLine("Enter a number: ");
var input = Console.ReadLine();
return int.Parse(input);
}
static bool ifPossible(int x, int y)
{
return x < y;
}
static void finalMethod(bool x)
{
if (x)
{
Console.Write("Success");
}
else
{
Console.Write("Fail");
}
}
var number1 = getInputValue();
var number2 = getInputValue();
finalMethod(ifPossible(number1, number2))
Couple of things in above code:
1.remove int return value from finalmethod
2. ifpossible is taking 1 argument it should take two.
class Program
{
static void Main(string[] args)
{
SomeClass.finalMethod(SomeClass.ifPossible(SomeClass.functionOne(), SomeClass.functionTwo()));
Console.ReadLine();
}
}
class SomeClass
{
internal static int functionOne()
{
int number;
Console.WriteLine("Enter a number: ");
number = int.Parse(Console.ReadLine());
return number;
}
internal static int functionTwo()
{
int number;
Console.WriteLine("Enter a number: ");
number = int.Parse(Console.ReadLine());
return number;
}
internal static bool ifPossible(int x, int y)
{
if (x < y)
{
return true;
}
else
{
return false;
}
}
internal static void finalMethod(bool x)
{
if (x)
{
Console.Write("Success");
}
else
{
Console.Write("Fail");
}
}
}

adding objects in a list, am i doing it right?

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

I need help on using an array made in one class in a different class and get its sum

In my Inputs class I have an array named score. I need to use it in my MathFun class and get the sum of it.
class Inputs
{
int amountgames;
public void AmountOfGames()
{
Console.WriteLine("How many games did you play?");
amountgames = int.Parse(Console.ReadLine());
}
public void Scores()
{
int[] score = new int[amountgames];
Console.WriteLine("score for game ");
for (int i = 0; i < score.Length; i++)
{
score[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("\nThe scores you entered are");
for (int j = 0; j < score.Length; j++)
{
Console.WriteLine(score[j]);
}
}
}
class MathFun
{
int number1;
int number2;
int total;
int averaged;
public int Average;
public int Added1;
public MathFun()
{
}
public void DivideThem()
{
Average = number1 / number2;
}
public void Added()
{
Added1 = inputs.score.sum();
//This is where in the array and its sum
}
public MathFun(int innumber1, int innumber2)
{
number1 = innumber1;
number2 = innumber2;
}
public int Number1
{
get
{
return number1;
}
set
{
number1 = value;
}
}
public int Number2
{
get
{
return number2;
}
set
{
number2 = value;
}
}
public int Total
{
get
{
return total;
}
}
public int Averaged
{
get
{
return averaged;
}
}
public void CalcTotal()
{
total = Added1;
averaged = Average;
}
}
You have two choices
Create an instance of Inputs that you can use in MathFun.
Make Scores() static, so that an instance is not required. If you do that, amountgames and AmountOfGames() will also have to become static.
Either way, you will have to return the inputs from Scores() or store them in some way in the class.
public int[] Scores()
{
int[] score = new int[amountgames];
Console.WriteLine("score for game ");
for (int i = 0; i < score.Length; i++)
{
score[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("\nThe scores you entered are");
for (int j = 0; j < score.Length; j++)
{
Console.WriteLine(score[j]);
}
}
return score;
}
Here's how you could approach it with the first approach
Inputs inputs = new Inputs();
int[] scores = Scores();
// Use scores with MathFun
NOTE: I would not generally create a function that is both responsible for writing scores out to the console and returning them. A single responsibility per method is preferred. The solution here is one that modifies your current code as little as possible.
Found my own solution
int sum = 0;
for (int i = 0; i < score.Length; i++)
{
sum += score[i];
}
add this to the array to add it all up
then just make an instance of sum

How to call method that is in a class

Learning C# on my own (not homework). I wrote a TotalDue method to calculate grand total of all customer balances due (from array). Placed it within the Customer class so it would have access to the data. I cannot figure out how to call this method in main. How do I get the total to display?
class Program
{
static void Main(string[] args)
{
Customer[] customers = new Customer[2];
string customer;
int id;
double due;
// GET DATA AND FILL ARRAY
for (int x = 0; x < customers.Length; ++x)
{
GetData(out customer, out id, out due);
customers[x] = new Customer(customer, id, due);
}
// SORT ARRAY - NEEDS ICOMPARABLE<Customer> - PART 1
Array.Sort(customers);
// PRINT ARRAY WITH TOSTRING() OVERRIDE
for (int x = 0; x < customers.Length; ++x)
{
Console.WriteLine(customers[x].ToString());
}
//DON'T KNOW HOW TO CALL THE TOTAL DUE METHOD...
Console.ReadLine();
}
class Customer : IComparable<Customer> // SORT ARRAY - PART 2
{
private string CustomerName { get; set; }
private int IdNumber { get; set; }
private double BalanceDue { get; set; }
// CONSTRUCTOR
public Customer(string customer, int id, double due)
{
CustomerName = customer;
IdNumber = id;
BalanceDue = due;
}
//SORT THE ARRAY - PART 3
public int CompareTo(Customer x)
{
return this.IdNumber.CompareTo(x.IdNumber);
}
// OVERRIDE TOSTRING TO INCLUDE ALL INFO + TOTAL
public override string ToString()
{
return ("\nCustomer: " + CustomerName + "\nID Number: " + IdNumber + "\nBalance Due: " + BalanceDue.ToString("C2"));
}
// TOTAL DUE FOR ALL CUSTOMERS
static void TotalDue(Customer [] customers)
{
double Total = 0;
for (int x = 0; x < customers.Length; ++x)
Total += customers[x].BalanceDue;
Console.WriteLine("Total Amount Due: {0}", Total.ToString("C2"));
}
}
// GET DATA METHOD
static void GetData(out string customer, out int id, out double due)
{
Console.Write("Please enter Customer Name: ");
customer = Console.ReadLine();
Console.Write("Please enter ID Number: ");
int.TryParse(Console.ReadLine(), out id);
Console.Write("Please enter Balance Due: $");
double.TryParse(Console.ReadLine(), out due);
}
}
Make TotalDue method public as the default access modifier in C# is private and then try this.
class Customer : IComparable<Customer> // SORT ARRAY - PART 2
{
public static void TotalDue(Customer [] customers)
{
double Total = 0;
for (int x = 0; x < customers.Length; ++x)
Total += customers[x].BalanceDue;
Console.WriteLine("Total Amount Due: {0}", Total.ToString("C2"));
}
}
static void Main(string[] args)
{
// ...........
//............
Customer.TotalDue(customers);
}
The default access modifier in C# is private. Since your TotalDue method does not specify anything else, it is private. You can change this to public and call it from your Main.
Add public access modifier with your static method and call it with name of class or remove the static keyword and make it instance and call class method.
make your Customer class method (TotalDue) Public and NOT static...

Categories

Resources