This question already has answers here:
max and min of array c#
(3 answers)
Closed 1 year ago.
I have a program to find the minimum and maximum grade. I The maximum function works but the minimum function returns 0. I'm not sure what I did wrong, there is no errors in my code. Thanks!
using System;
using System.Collections.Generic;
namespace GradeConverter
{
class Program
{
static void Main(string[] args)
{
bool doAgain = true;
//float totalScore = 0 , averageScore;
string moreConversions;
int numberOfGrades;
//Ask the user to enter their first and last name
string userName = getName();
//Print a welcome message: "Hello [first name] [last name] Welcome to the Grade Converter!"
Console.WriteLine($"\nHello {userName}! Welcome to the Grade Converter!");
while(doAgain){
List<float> scores = new List<float>();
//Prompt the user to enter the number of grades they need to convert "Enter the number of grades you need to convert: "
numberOfGrades = getNumberOfGrades();
//Prompt the user to enter the grades. The grades should be stored in a list and you should use the appropriate data type for the grades.
scores = populateGradesList(scores, numberOfGrades);
//Print Grade Report
printGradeReport(scores);
printGradeStatistics(scores, numberOfGrades);
float aveScore = getAverageGrade(scores);
float maximumGrade = getMaximumGrade(scores);
float minimumGrade = getMinimumGrade(scores);
//averageScore = totalScore / numberOfGrades;
Console.WriteLine("Would you like to convert more grades (y/n)?");
moreConversions = Console.ReadLine();
//reset total score
//totalScore = 0;
if (moreConversions != "y" && moreConversions != "Y"){
doAgain = false;
}
}
}
static float getMinimumGrade(List<float> listOfNumberGrades){
float min = 0;;
foreach(float grade in listOfNumberGrades){
if( grade < min){
min = grade;
}
}
return min;
}
static float getMaximumGrade(List<float> listOfNumGrades){
float max = 0;
foreach(float grade in listOfNumGrades){
if( grade > max){
max = grade;
}
}
return max;
}
static float getAverageGrade(List<float> listOfGrades){
float total = 0;
float average = 0;
foreach(float grade in listOfGrades){
total += grade;
}
average = total / listOfGrades.Count;
return average;
}
static void printGradeStatistics(List<float> listOfGrades, int numberOfGrades){
float averageScore = getAverageGrade(listOfGrades);
float maximumGrade = getMaximumGrade(listOfGrades);
float minimumGrade = getMinimumGrade(listOfGrades);
Console.WriteLine("\nGrade Statistics\n-------------------------\n");
Console.WriteLine($"Number of grades: {numberOfGrades}");
Console.WriteLine($"Average Grade: {averageScore} which is a {getLetterGrade(averageScore)}");
Console.WriteLine($"Maximum Grade: {maximumGrade}");
Console.WriteLine($"Minimum Grade: {minimumGrade}");
}
static void printGradeReport(List<float> scoresList){
string letterGrade;
Console.WriteLine();
foreach(float testScore in scoresList){
//Convert the number grades to letter grades (A = 90-100, B = 80-89, C = 70-79, D = 60 - 69, F lower than 60)
letterGrade = getLetterGrade(testScore);
//Print all the numerical grades and their corresponding letter grades to the console
Console.WriteLine($"A score of {testScore} is a {letterGrade} grade");
}
return;
}
static List<float> populateGradesList(List<float> listOfScores, int numGrades){
float score;
for(int counter = 0; counter < numGrades; counter ++){
score = getScores();
listOfScores.Add(score);
}
return listOfScores;
}
static int getNumberOfGrades(){
Console.WriteLine("\nEnter the number of grades you need to convert:");
int numberOfGrades = int.Parse(Console.ReadLine());
return numberOfGrades;
}
static string getName(){
Console.WriteLine("Please enter your first name and last name");
string userName = Console.ReadLine();
return userName;
}
static float getScores(){
float grade;
while(true){
Console.WriteLine("\nEnter the score to be converted: ");
try{
grade = float.Parse(Console.ReadLine());
break;
}catch(FormatException){
Console.WriteLine("Error: Only numbers allowed");
}
}
return grade;
}
static string getLetterGrade(float score){
//(A = 90-100, B = 80-89, C = 70-79, D = 60 - 69, F lower than 60).
if (score >= 90){
return "A";
}else if(score >= 80){
return "B";
}else if (score >= 70){
return "C";
}else if(score >= 60){
return "D";
}else{
return "F";
}
}
}
}
You could set the starting value as the first one in the list. Something like this:
static float getMinimumGrade(List<float> listOfNumberGrades){
float min = listOfNumberGrades.First();
foreach(float grade in listOfNumberGrades){
if( grade < min){
min = grade;
}
}
return min;
}
Note though, that this doesn't work if there are 0 items in the list, also, it accesses the first item in the list first.
An even easier way, is to use IEnumerable.Min:
static float getMinimumGrade(List<float> listOfNumberGrades){
return listOfNumberGrades.Min();
}
I am working on a school project and I am stuck. I am trying to get some info from the user and calculate a few things with the inputted information from the user.
I had my code running, but my teacher told me I needed to replace the calculations to my logic layer (they were in my controller). I am trying to do that, but I am stuck.
This is my controller:
public class CalculatorController : Controller
{
// GET: Calculator
public ActionResult PackCalculator()
{
return View(new CalculatorModel());
}
[HttpPost]
public ActionResult PackCalculator(CalculatorModel calculator)
{
CalculatorLogic x = new CalculatorLogic();
int Y = x.calculator(new CalculatorModel());
return View(calculator);
}
And this is the class in the logic layer:
namespace ApexLogic
{
public class CalculatorLogic
{
public int calculator(CalculatorModel calculator)
{
if (calculator.CurrentLevel < 21)
{
calculator.CurrentPack = calculator.CurrentPack + (calculator.CurrentLevel - 1);
int seizoenPacks = calculator.PlayedSeasons * 5;
int BattlepassPacks = calculator.Battlepass * 12;
int CurrentPack = calculator.CurrentPack + seizoenPacks + BattlepassPacks + calculator.BoughtPacks;
return CurrentPack;
}
else if (calculator.CurrentLevel > 21 && calculator.CurrentLevel < 301)
{
int CurrentLevelPack = calculator.CurrentLevel - 20;
int PackCalculator2 = (calculator.CurrentLevel / 2);
int CurrentLevelPack2 = PackCalculator2 + 19;
int seizoenPacks = calculator.PlayedSeasons * 5;
int BattlepassPacks = calculator.Battlepass * 12;
calculator.CurrentPack = calculator.CurrentPack + seizoenPacks + BattlepassPacks +
calculator.BoughtPacks + CurrentLevelPack2;
return calculator.CurrentPack;
}
else if (calculator.CurrentLevel > 300 && calculator.CurrentLevel <= 500)
{
int CurrentLevelPack = calculator.CurrentLevel - 300;
int PackCalculator2 = (CurrentLevelPack / 5);
int CurrentLevelPack2 = PackCalculator2 + 159;
int seizoenPacks = calculator.PlayedSeasons * 5;
int BattlepassPacks = calculator.Battlepass * 12;
calculator.CurrentPack = calculator.CurrentPack + seizoenPacks + BattlepassPacks +
calculator.BoughtPacks + CurrentLevelPack2;
return calculator.CurrentPack;
}
else
{
return 0;
}
}
}
When I try and use the breakpoint to see where it goes wrong I can see that the input from the user is being directed correctly to the class, but my calculations are not being done and I always get 0 returned back. I have no idea what to do now (usually I get it fixed with breakpoints, but they are not helping me)
The user input
It is handled correctly as you can see
But my Y in the controller always stays zero.
It makes no difference if I use the way of return like in the first If statements or if I use the way of return in the second or third if statement.
Can someone help me?
You are passing a new CalculatorModel into your call to your application logic class:
int Y = x.calculator(new CalculatorModel()); //This is what is messing you up
Change it to this:
int Y = x.calculator(calculator); //Use the model parameter which is passed into your Post method
Your model was null , First you must fill your model. Change your code like this,
[HttpPost]
public ActionResult PackCalculator(CalculatorModel calculator)
{
CalculatorLogic x = new CalculatorLogic();
int Y = x.calculator(new CalculatorModel());
return View(calculator);
}
[HttpPost]
public ActionResult PackCalculator(CalculatorModel calculator)
{
CalculatorLogic x = new CalculatorLogic();
var model = new CalculatorModel(){
CurrentLevel = 12,
CurrentLevelPack = 10 .....
};
int Y = x.calculator(model);
return View(calculator);
}
I'm working on an assignment for school that consists of both a Program.cs file and a separate class called Car. I have written all code for the Car class and pasted already provided code into the program.cs file. The resulting output is
2010 Ford Focus is going 20 MPH.
2018 Chevy Cruze is going 0 MPH.
The assignment calls for an expected output of
2010 Ford Focus is going 28 MPH.
2018 Chevy Cruze is going 18 MPH.
I need to know how to get the window to output the expected speed of 28 for Car 1 and 18 for car 2. I'm assuming that I'm not supposed to alter the code that was provided for program.cs to accomplish the right output for the application/assignment.
public class Car
{
private int Speed;
private string Make;
private string Model;
private int Year;
public Car (string make, string model, int year, int speed)
{
this.Make = make;
this.Model = model;
this.Year = year;
this.Speed = speed;
}
public Car(string make, string model, int year)
{
this.Make = make;
this.Model = model;
this.Year = year;
this.Speed = 0;
}
public int SpeedUp()
{
this.Speed = Speed++;
return (Speed);
}
public int SlowDown()
{
if (Speed > 0)
{
this.Speed = Speed--;
}
return (Speed);
}
public void Display()
{
Console.WriteLine(Year + " " + Make + " " + Model + " is going " + Speed + " MPH.");
Convert.ToString(Console.ReadLine());
}
}
and here is the given code that goes in program.cs
class Program
{
static void Main(string[] args)
{
int car1Speed = 20;
int car2Speed = 0;
Car car1 = new Car("Ford", "Focus", 2010, car1Speed);
Car car2 = new Car("Chevy", "Cruze", 2018, car2Speed);
for (int i = 0; i < 60; i++)
{
if (i % 2 == 0)
{
car2Speed = car2.SpeedUp();
}
if (i % 3 == 0)
{
car1Speed = car1.SpeedUp();
}
if (i % 5 == 0)
{
car1Speed = car1.SlowDown();
car2Speed = car2.SlowDown();
}
}
car1.Display();
car2.Display();
}
}
The line of code
this.Speed = Speed++;
Has no effect on the value of this.Speed.
The line of code is roughly equivalent to
int temp = this.Speed; // We store the original value of Speed.
this.Speed = Speed + 1; // We add one to Speed and assign it back to Speed.
this.Speed = temp; // We immediately replace Speed with the original value of Speed.
This is the due to the behavior of the '++' operator which, when appended to the end of a variable will add 1 to its current value and then assigns the result back to the variable. This operator however temporarily stores the original value and uses that as the result of the expression. This temporary result of the ++ operator is ultimately what you are assigning to this.Speed due to the '=' operator you're using in the same expression, this in turn is what is causing the variable to not actually be modified.
The correct usage would be to simply call
Speed++;
This will perform the addition of 1 and assignment back to Speed, and also discard the temporary variable, as it is not being assigned anywhere.
This issue also exists in your SpeedDown method with the '--' operator.
In your Car.cs class, here is a better way to increment the speed without modifying the Program.cs file:
public int SpeedUp()
{
this.Speed += 1;
return (Speed);
}
public int SlowDown()
{
if (Speed > 0)
{
this.Speed -= 1;
}
return (Speed);
}
That produces the output that you're after.
I am a student in my first year of CIS courses, so I am a begineer. We are supposed to get input from a text file with an employee, the employee's department, hourly salary, and hours worked in given week, that looks like:
EID001, 1, 10.00, 40
EID002, 2, 10.50, 35
EID003, 3, 11.00, 30
EID004, 4, 11.50, 25
EID005, 5, 12.00, 20
EID006, 6, 12.50, 40
EID007, 7, 11.00, 25
.
.
.
(Employee ID, Department, Hourly Salary, Hours Worked)
Then separate each field into elements of an array, validate each field, and calculate the total gross pay (Hourly Salary * Hours Worked) for each of the 7 departments.
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Project_3_rev
{
class Program
{
const int DEPARTMENTS = 7;
const int FIELDS = 4;
static void Main(string[] args)
{
FileStream fStream = new FileStream("project3data.txt", FileMode.Open, FileAccess.Read);
StreamReader inFile = new StreamReader(fStream);
string input = "";
string[] fields = new string[FIELDS];
string employee = "";
int department = 0;
double salary = 0.00;
int hours = 0;
double totalSalary = 0.00;
int totalHours = 0;
double[] grossPayArray = new double[DEPARTMENTS];
input = inFile.ReadLine();
while(input != null)
{
fields = input.Split(',');
checkEmployee(input, fields, employee);
checkDepartment(input, fields, department);
for(int x = 1; x <= DEPARTMENTS; x++)
{
totalSalary = 0.00;
totalHours = 0;
while (department == x)
{
checkSalary(input, fields, salary, department, totalSalary);
checkHours(input, fields, hours, department, totalHours);
grossPayArray[x - 1] = totalSalary * totalHours;
}
}
input = inFile.ReadLine();
}
displayOutput(grossPayArray);
}
static void checkEmployee(string inp, string[] fieldsArray, string emp)
{
if(fieldsArray[0] == null)
Console.WriteLine("An Employee ID is invalid.");
}
static void checkDepartment(string inp, string[] fieldsArray, int dept)
{
if((!int.TryParse(fieldsArray[1], out dept)) || dept < 0 || dept > DEPARTMENTS)
{
Console.WriteLine("Department field is invalid: " + fieldsArray[1]);
}
}
static void checkSalary(string inp, string[] fieldsArray, double sal, int dept, double totSal)
{
if ((double.TryParse(fieldsArray[2], out sal)) && sal >= 10.00)
totSal = totSal * sal;
else
Console.WriteLine("Salary field is invalid: " + fieldsArray[2]);
}
static void checkHours(string inp, string[] fieldsArray, int hrs, int dept, int totHrs)
{
if ((int.TryParse(fieldsArray[3], out hrs)) && hrs >= 0)
totHrs = totHrs * hrs;
else
Console.WriteLine("Hours field is invalid: " + fieldsArray[3]);
}
static void displayOutput(double[] grossArray)
{
for(int x = 1; x <= DEPARTMENTS; x++)
{
Console.WriteLine("Department " + x + ": Gross Pay = " + grossArray[x-1]);
}
}
}
}
My output:
Department 1: Gross Pay = 0
Department 2: Gross Pay = 0
Department 3: Gross Pay = 0
Department 4: Gross Pay = 0
Department 5: Gross Pay = 0
Department 6: Gross Pay = 0
Department 7: Gross Pay = 0
Why are the Gross Pays equaling zero?
Please keep in mind that I am in my first year of computer science. I am only allowed to use what we have learned and I only know the basics. Please cut me a little slack if this code is messy or my logic is way off. Thanks ahead of time.
In these two lines of code:
totalSalary = 0.00;
totalHours = 0;
you set the values to zero. Multiplying them by anything later, will still be zero. You need to make sure you either update these fields with the correct values before multiplying, or at the very least set them to 1.
The problem of your code is this kind of function:
static void checkSalary(string inp, string[] fieldsArray, double sal, int dept, double totSal)
{
if ((double.TryParse(fieldsArray[2], out sal)) && sal >= 10.00)
totSal = totSal * sal;
else
Console.WriteLine("Salary field is invalid: " + fieldsArray[2]);
}
Is similar to this kind of function:
function Increase(int number) {
number = number + 1;
}
var number = 5;
Increase(number);
Console.WriteLine(number);
What you get is 5, instead of your expectation, 6.
In C#, it's called "passed by value". The value is passed into the function, and no modification is affected to the outside variable. In your case, toSalary will remain 0.
YOu need to change to ref double toSalary to use "pass by reference".
Other thing you need to practice is debugging technique:
Put break point.
Print the value to check.
Write unit tests to verify your methods.
Looks like you are multiplying 'grossPayArray[x - 1] = totalSalary * totalHours;' correctly, but it appears you are not updating totalSalary or totalHours from the initial value of 0.
You will need to read the file.
Split the values.
Update the variables, from zero.
Perform your function, in this case, multipling.
Hope that helps
The problem is here:
for(int x = 1; x <= DEPARTMENTS; x++)
{
totalSalary = 0.00;
totalHours = 0;
while (department == x)
{
checkSalary(input, fields, salary, department, totalSalary);
checkHours(input, fields, hours, department, totalHours);
grossPayArray[x - 1] = totalSalary * totalHours;
}
}
Notice that you never change the variables totalSalary and totalHours.
What I suggest you do is redefine your functions to only validate the input salary:
static void validateSalary(string inp, string[] fieldsArray, double sal, int dept, double totSal)
{
// you might want to rewrite this
if !((double.TryParse(fieldsArray[2], out sal)) && sal >= 10.00)
Console.WriteLine("Salary field is invalid: " + fieldsArray[2]);
}
This way, the function actually only validates the salary, as it was named. See: Single Responsibility Principle
Then set your total salary within the loop itself:
while (department == x)
{
checkSalary(input, fields, salary, department, totalSalary);
checkHours(input, fields, hours, department, totalHours);
totalSalary *= salary;
totalHours += hours;
grossPayArray[x - 1] = totalSalary * totalHours;
}
EDIT: Of course, this still has the problem that salary doesn't change within the loop.
This type of question might be better in the Code Review section of StackExchange.
Nonetheless, for your reference later in the year, here's an example solution using classes and LINQ:
To run:
var app = new App_DepartmentPay();
app.Run();
Output:
using System;
using System.IO;
using System.Linq;
namespace StackOverflow
{
public class App_DepartmentPay
{
public void Run()
{
var lines = File.ReadAllLines(#"d:\temp\payments.txt");
var payStubs = lines.Select(l => new PayStub(l)).ToList();
var departmentTotals = payStubs.GroupBy(p => p.Department).Select(g => new DepartmentTotal(g.Key, g.Sum(w => w.Pay))).ToList();
departmentTotals.ForEach(t => Console.WriteLine(t.ToString()));
}
}
public class PayStub
{
public string EmployeeId { get; private set; }
public int Department { get; private set; }
public decimal HourlyWage { get; private set; }
public decimal HoursWorked { get; private set; }
public decimal Pay
{
get
{
return HourlyWage * HoursWorked;
}
}
public PayStub(string payLine)
{
var contents = payLine.Split(',');
EmployeeId = contents[0];
Department = int.Parse(contents[1]);
HourlyWage = decimal.Parse(contents[2]);
HoursWorked = decimal.Parse(contents[3]);
}
}
public class DepartmentTotal
{
public int Department { get; set; }
public decimal TotalPay { get; set; }
public DepartmentTotal(int department, decimal pay)
{
Department = department;
TotalPay = pay;
}
public override string ToString()
{
return $"Department: {Department} \tGross Pay: {TotalPay}";
}
}
}
Hi I am getting invalid cast from double to datetime error when i run my ASP.NET MVC code.
This is my code :
Update: Hi I am adding my full code below. Please have a look into that.
Boolean locked = false;
if (frmcollection["lockStart"] != null && frmcollection["lockStart"] != "")
{
locked = Convert.ToBoolean(frmcollection["lockStart"].ToString());
}
else if (datelock == "")
{
locked = Convert.ToBoolean("0");
}
Boolean valid = true;
double inteval = 86400000 * Convert.ToDouble(frmcollection["autoFrequency"].ToString());
DateTime schedulestartDate = Convert.ToDateTime(frmcollection["autoStart"].ToString());
int startHour = Convert.ToInt32(frmcollection["autoStartHour"].ToString());
DateTime sd = schedulestartDate;
sd.AddHours(startHour);
DateTime filterStart = Convert.ToDateTime(frmcollection["periodStart"].ToString());
int filterStartHour = Convert.ToInt32(frmcollection["periodStartHour"].ToString());
DateTime fsd = filterStart;
fsd.AddHours(filterStartHour);
DateTime filterEnd = Convert.ToDateTime(frmcollection["periodEnd"].ToString());
int filterEndHour = Convert.ToInt32(frmcollection["periodEndHour"].ToString());
DateTime fed = filterEnd;
fed.AddHours(filterEndHour);
double sDate = sd.Second;
double sPeriod = sDate - fsd.Second;
double ePeriod = sDate - fed.Second;
if (sPeriod < ePeriod || sPeriod < 0 || ePeriod < 0)
{
valid = false;
}
if (valid)
{
for (int i = 0; i < 5; i++)
{
DateTime date = Convert.ToDateTime(sDate + (inteval * i));
if (locked)
{
DateTime psdate = Convert.ToDateTime(sDate - sPeriod);
}
else
{
DateTime psdate = Convert.ToDateTime(sDate + (inteval * i) - sPeriod);
}
DateTime pedate = Convert.ToDateTime(sDate + (inteval * i) - ePeriod);
}
}
else
{
}
When i debug I am gettin error in this line :
DateTime date = Convert.ToDateTime(sDate + (inteval * i));
Can someone help me in this??
You're adding a double to whatever interval * i resolves to.
You can't convert (cast) that to a DateTime, which is exactly what the error is telling you.
It seems as if you're looking for the date some (interval * i) seconds after the date "sd". If so, try:
for (int i = 0; i < 5; i++)
{
DateTime date = sd.AddSeconds(inteval * i);
if (locked)
{
DateTime psdate = sd.AddSeconds(-sPeriod);
}
else
{
DateTime psdate = sd.AddSeconds((inteval * i) - sPeriod));
}
DateTime pedate = sd.AddSeconds((inteval * i) - ePeriod);
}
//...
DateTime has a lot of methods to perform calculations on a specific date. For example DateTime.AddMillisecons which takes a double and returns a date.
MSDN DateTime.AddMilliseconds