how to display each course entered in while loop? C# - c#

I'm unsure how to display each course the user enters. As it stands only the last course entered gets displayed. What am I not thinking about?
while (quit != "0")
{
//get user data
Console.WriteLine("Enter course # {0}:", counter);
course = Console.ReadLine();
Console.WriteLine("Enter grade value of 1-4 # {0}:", counter);
grade = Convert.ToInt32 (Console.ReadLine());
Console.WriteLine("Enter credit hours from 1-3 # {0}:",counter);
creditHours = Convert.ToInt32 (Console.ReadLine());
//calculate grade * creditHours and store in gradePoints
gradePoints = grade * creditHours;
//running total of credit hours and grades
totalGradePoints += gradePoints;
totalCreditHours += creditHours;
Console.WriteLine("Press '0' to quit or any key to continue.");
quit = Console.ReadLine();
counter++;// adds one to counter
}//end while
// calculate gpa
double GPA = totalGradePoints / totalCreditHours;
//display course(s) credit hours and gpa
Console.WriteLine("Course(s): {0}", course);
Console.WriteLine("Credit hours: {0}",totalCreditHours);
Console.WriteLine("GPA: {0:n2}",GPA);

You need to move
Console.WriteLine("Course(s): {0}", course);
inside of your while loop. You are only displaying it after the loop ends. So that's why you see the last course.
If you don't want to display them immediately, then store the courses into a collection and iterate over the collection after while loop and display them:
var courses = new List<string>();
while(...)
{
...
course = Console.ReadLine();
courses.Add(course);
...
}
foreach(var c in courses)
Console.WriteLine(c);

You're setting variables inside a while loop, therefore that same variable gets overridden with each iteration of the loop.
Instead, try using a List<T> object or an array, both of which can hold multiple values, and consider making a class for your data, since it's all associated:
class CourseData
{
public string Course { get; set; }
public int Grade { get; set; }
public nt CreditHours { get; set; }
public int GradePoints { get { reutrn Grade * CreditHours; } }
}

Related

I want to write a program that calculates the sum and average of student grades

Having problem with my work i want to write a program that does the sum and average the student grade in the average function i used a do while loop since i want anyone to enter grade until the user enter -1 the loop end.
The problem is i do not want to run the _cal = Int32.Parse(Console.ReadLine()); in the fucntion instead run it in the main by passing a value to Average() parameter then using the value in main as a console.readlIne because i will use the user input to divide by the sum in order to get average am new to programming.
public static void Main()
{
Console.WriteLine("Please Enter the scores of your student: ");
Console.WriteLine("----------------------------------------");
_studentTotalGrade = Average();
Console.WriteLine("sum " + Sum);
Console.ReadLine();
}
public static double Average()
{
double _cal,_sumTotal = 0;
int i = 0;
do
{
_cal = Int32.Parse(Console.ReadLine());
if (_cal == -1)
{
break;
}
if (_cal > 20)
{
Console.WriteLine("Adjust score\");
continue;
}
_sumTotal +=_cal;
i--;
} while (_cal > i);
return _sumTotal;
}
}

loops for prevent duplicate input to an array [duplicate]

This question already has answers here:
Using .Contains() on a property in a list
(8 answers)
Closed 5 years ago.
So, for our c# class we have to create an array of 5 objects, that have 4 properties
an int for job number
a string for job name
a string for job description
a double for expected hours of the job.
I need in my loop a way to prevent the user from entering a duplicate job number: here is my code so far. This code works, but will allow duplicate job numbers;
namespace JobDemo2
{
class Program
{
static void Main(string[] args)
{
Job[] jobbies = new Job[5];
int x;
int jobNum;
string customerName;
string description;
double hours;
const double RATE = 45.00;
for (x = 0; x < jobbies.Length; ++x)// creates array
{
GetJobData(out jobNum, out customerName, out description, out hours, jobbies);
jobbies[x] = new Job(jobNum, customerName, description, hours);
}
//Array.Sort(jobbies);
Console.WriteLine("The jobs, sorted, are: ");
for (x = 0; x < jobbies.Length; ++x) // prints the array values
{
DisplayJobs(jobbies[x]);
}
double totalRevenue = (jobbies[0].Hours + jobbies[1].Hours +
jobbies[2].Hours + jobbies[3].Hours + jobbies[4].Hours) * RATE;
Console.WriteLine();
Console.WriteLine("The total revenue projected is {0}", totalRevenue);
Console.ReadKey();
}
static void GetJobData(out int jobNum,
out string customerName, out string description, out double hours,
Job[] jobbies)
{
string inString;
Console.Write("Please enter a job number >> ");
inString = Console.ReadLine();
int.TryParse(inString, out jobNum);
Console.Write("Please enter the customer's name for this job >> ");
customerName = Console.ReadLine();
Console.Write("Please enter the job's description >> ");
description = Console.ReadLine();
Console.Write("Please enter the projected hours for the job >> ");
inString = Console.ReadLine();
double.TryParse(inString, out hours);
Console.WriteLine();
}
static void DisplayJobs(Job jobbies)
{
Console.WriteLine("{0, 5} {1, -10} {2, 6} {3, 8}",
jobbies.JobNumber, jobbies.Customer, jobbies.Description, jobbies.Hours);
}
}
class Job //object
{
private double hours;
private double price;
public const double RATE = 45.00;
public Job(int num, string cust, string desc, double hrs)
{
JobNumber = num;
Customer = cust;
Description = desc;
Hours = hrs;
}
public int JobNumber { get; set; }
public string Customer { get; set; }
public string Description { get; set; }
public double Hours
{
get
{
return hours;
}
set
{
hours = value;
price = hours * RATE;
}
}
public double Price
{
get
{
return price;
}
}
public override string ToString()
{
return (GetType() + " " + JobNumber + " " + Customer + " " +
Description + " " + Hours + " hours #" + RATE.ToString("C") +
" per hour. Total price is " + Price.ToString("C"));
}
public override bool Equals(Object e)
{
bool equal;
Job temp = (Job)e;
if (JobNumber == temp.JobNumber)
equal = true;
else
equal = false;
return equal;
}
public override int GetHashCode()
{
return JobNumber;
}
}
}
the teacher is suggesting to the class that we ad another for loop here that compares the objects. What would that for loop look like?
Here is her email:
help for the looping create a boolean variable.
for loop through your array to ask the user to enter info and set your bool variable to true.
another for loop inside to call the equals method in the class that will compare the job just entered to each object in In the array. This is where most are messing up because you must compare objects to objects and not an interger for job number to an entire object. if the objects equal set the bool to false.
while the bool is false you want to tell them they entered a wrong number and to enter again. Set the bool to true in here and go the same for loop to compare again. as long as the number stays false the user will be stuck in this while loop. when they enter a correct number it will break out.
This is homework, so I'll only give you some pointers:
Don't hand in the array (jobbies) storing the jobs to GetJobData. This method should have only one concern: getting job data. Figuring out if the data has a duplicate Id is not it's concern.
Write a helper method that checks for duplicates. What does it need? It needs all previous jobs, how many there are, and the new job it needs to validate. The following signature looks about right:
private static bool CheckIfNewJobIsValid(Job newJob,
Job[] jobs,
int jobsValidatedCount)
What does this method have to do? Well, it only needs to loop through the first jobsValidatedCount jobs in jobs and check if newJob equals any of them. If it does, bail out returning false. If the loop finishes then you can return true, no match was found.
jobsValidatedCount doesn't need to be a new counter, maybe some other already existing variable in the code can give you that info already.
Good luck!
P.D. Because this was already handed down by your teacher, I'll fix up the Equals method just a little:
public override bool Equals(Object e)
{
bool equal = false;
Job temp = e as Job;
if (Job != null && JobNumber == temp.JobNumber)
{
equal = true;
}
return equal;
}
P.D. As Alexei Levenkov points out in comments, using Equals ony for JobNumber comparisson seems a bad idea. Are any two jobs with the same JobNumber really equal regardless of the value of all other properties? That could be confusing to say the least. A better approach would be to directly check JobNumber inside CheckIfNewJobIsValid and not use Equals but I guess its use is due to academic reasons.

How to display a max, min, and average result from an array in c#?

Basically I have to write a program that asks a user to name the amount of players on their football team, list their names and how many goals they have scored. The output should then be "the top player is..with a score of .. The average goals scored is.. The lowest goals scored is.."
We haven't really covered arrays properly yet, but I have started this question now and it will drive me crazy until I get it done. I know I am probably a good bit away from getting what I need but any point in the right direction would be really appreciated! P.S I know the last bit of my code is completely wrong I just don't know where to go from here. My code:
Console.WriteLine("Enter the amount of players");
int amount = int.Parse(Console.ReadLine());
string[] names = new string[amount];
int[] playerGoals = new int[amount];
int result;
string playerName;
for (int i = 0; i < playerGoals.Length; i++)
{
Console.WriteLine("Enter a players name");
playerName = Console.ReadLine();
names[i] = playerName;
Console.WriteLine("Enter how many goals they have score this season");
result = int.Parse(Console.ReadLine());
playerGoals[i] = result;
}
int minimum = playerGoals.Min();
int maximum = playerGoals.Max();
double average = playerGoals.Average();
Console.WriteLine("The top player is {0} with a score of {1}", maximum);
Console.WriteLine("");
Console.WriteLine("The average goals scored is {0}", average);
Console.WriteLine("");
Console.WriteLine("The lowest goal scored is {1}");
Console.ReadLine();
Here are some approaches you could take:
Look up the player with the max score
string maxPlayer = names[Array.IndexOf(playerGoals, maximum)];
Calculate the max yourself in a loop (either as you're taking the inputs or afterward), in a way that you keep track of the player along with it.
Create a PlayerStats class so you have one array (PlayerStats[]) instead of two, and use MoreLINQ's MaxBy. This would end up with the best code in my opinion, but is possibly more advanced than you're ready for (knowing how to do things manually is a good skill to have, although you don't always use it in the real world).
var best = playerStats.MaxBy(x => x.Goals);
Console.WriteLine("The top player is {0} with a score of {1}",
best.Name, best.Goals);
public class PlayerStats
{
public string Name { get; set; }
public int Goals { get; set; }
}
class Player
{
public string Name { get; set; }
public int goals { get; set; }
}
static void Main(string[] args)
{
Console.WriteLine("Enter the amount of players");
int amount = int.Parse(Console.ReadLine());
List<Player> _players = new List<Player>();
for (int i = 0; i < amount; i++)
{
Player objPlayer = new Player();
Console.WriteLine("Enter a players name");
objPlayer.Name = Console.ReadLine();
Console.WriteLine("Enter how many goals they have score this season");
objPlayer.goals = int.Parse(Console.ReadLine());
_players.Add(objPlayer);
}
int maxgoals = _players.Max(t => t.goals);
var maxplayer = _players.FirstOrDefault(t => t.goals == maxgoals).Name;
int mingoals = _players.Min(t => t.goals);
var minplayer = _players.FirstOrDefault(t => t.goals == maxgoals).Name;
var average = _players.Sum(t=>t.goals)/amount;
Console.WriteLine("The top player is {0} with a score of {1}", maxplayer, maxgoals);
Console.WriteLine("");
Console.WriteLine("The bottom player is {0} with a score of {1}", minplayer, mingoals);
Console.WriteLine("");
Console.WriteLine("The average goals scored is {0}", average);
Console.ReadLine();
}

C# console application - commission calculator - how to use method within method

I'm new to C# and I have encountered some problems with my console application that I'm recently working on. I am trying to have 3 methods:
getsales to get the sales the user made, calcCom to calculate the commission for the sales and finally main to make them work and establish the program.
I'm having trouble to make those methods work with(in) each other.
After i entered all the sales, the program goes to the else-statement and tells me "invalid entry". Since i haven't really gotten to output the variables I didn't expect any kind of output, but I want the program to tell the user the commission and sale for each person.
Please excuse me if I misused any terms or words, like I said I am new to this language! :D
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication38
{
class Program
{
public static void getsales ()
{
string inputsales;
double total = 0;
double sale = 0;
for (int salecount = 1; salecount <= 3; ++salecount)
{
Console.WriteLine("Enter sale: ");
inputsales = Console.ReadLine();
sale = Convert.ToDouble(inputsales);
total = total + sale;
Console.WriteLine();
}
}
public static void calcComm ()
{
double total = 0;
double comm = 0;
comm = total * 0.2;
}
static void Main()
{
Console.WriteLine(" Sunshine Hot Tubs \n Sales Commissions Report\n");
char Letter;
string name;
const string name1 = "Andreas";
const string name2 = "Brittany";
const string name3 = "Eric";
string inputLetter;
Console.WriteLine("Please enter intial or type z to quit");
inputLetter = Console.ReadLine();
Letter = Convert.ToChar(inputLetter);
while (Letter != 'z')
{
if (Letter == 'a')
{
name = name1;
getsales();
calcComm();
}
if (Letter == 'b')
{
name = name2;
getsales();
calcComm();
}
if (Letter == 'e')
{
name = name3;
getsales();
calcComm();
}
else
{
Console.WriteLine("Invalid entry try again");
inputLetter = Console.ReadLine();
}
}
}
}
}
I think your problem is you need this:
if (Letter == 'a')
{
name = name1;
getsales();
calcComm();
}
else if (Letter == 'b')
{
name = name2;
getsales();
calcComm();
}
else if (Letter == 'e')
{
name = name3;
getsales();
calcComm();
}
else
{
Console.WriteLine("Invalid entry try again");
inputLetter = Console.ReadLine();
}
You also need to copy this code after the else block, at the very end of your while loop.
Console.WriteLine("Please enter intial or type z to quit");
inputLetter = Console.ReadLine();
Letter = Convert.ToChar(inputLetter);
Also, remove this line from inside the else block. It isn't needed.
inputLetter = Console.ReadLine();
You probably intended to display the commision on the console. Change your getsales and calcComm to look like this:
public static void getsales ()
{
string inputsales;
double total = 0;
double sale = 0;
for (int salecount = 1; salecount <= 3; ++salecount)
{
Console.WriteLine("Enter sale: ");
inputsales = Console.ReadLine();
sale = Convert.ToDouble(inputsales);
total = total + sale;
Console.WriteLine();
}
calcComm(total);
}
public static void calcComm (double total)
{
double comm = 0;
comm = total * 0.2;
Console.WriteLine(comm);
}
Then remove all calls to calcComm from the Main method.
The variable "total" is in the two methods and they do not persist the data that you are looking for between the two methods that you have defined. That is, the total variable in getSales() method is different from calcComm() method.
You should move this:
double total = 0;
outside of the two methods and put it within the class with a static scope. Like:
class Program
{
static double total;
Also, reinitialize total to zero within your getSales() method.
calcComm() doesn't do anything...
I think you might want to have some of your variables as global so that if they are modified by a method you can still retrieve their value, or even better pass them to the method and get them returned with the new values.
To declare global variables you should declare them inside the class Program but outside any method and then make sure that no other methods have variables with the same name

Can someone turn this array code into a non-array method to acheive the same results?

I have here a piece of code that record the number of bottles collected by 4 rooms. When the user types in quit, the program spits out the number of bottles collect by each room and determines the room with the highest number of bottles collected. I have used an array method, but to I shouldn't use this method, just to show how useful array are. Can anyone give me any pointers?
namespace BottleDrive
{
class Program
{
static void Main(string[] args)
{//Initialize array of rooms to 4
int[] rooms = new int[4];
//Start of while loop to ask what room your adding into.
while (true)
{
Console.Write("Enter the room you're in: ");
//If user enters quit at anytime, the code will jump out of while statement and enter for loop below
string quit = Console.ReadLine();
if (quit == "quit")
//Break statement allows quit to jump out of loop
break;
//Variable room holds the number of bottles collect by each room.
int room = int.Parse(quit);
Console.Write("Bottles collected in room {0}: ", room);
// This line adds the count of bottles and records it so you can continuously count the bottles collected.
rooms[room - 1] += int.Parse(Console.ReadLine());
}
//This for statement lists the 4 rooms and their bottle count when the user has entered quit. An alternative to below
/*for (int i = 0; i < rooms.Length; ++i)
Console.WriteLine("Bottles collected in room {0} = {1}", i + 1, rooms[i]);*/
int maxValue = 0;//initiates the winner, contructor starts at 0
int maxRoomNumber = 0;//initiates the room number that wins
for (int i = 0; i < rooms.Length; ++i)//This loop goes through the array of rooms (4)
{
if (rooms[i] > maxValue)//Makes sure that the maxValue is picked in the array
{//Looking for room number for the
maxValue = rooms[i];
maxRoomNumber = i + 1;
}//Writes the bottles collected by the different rooms
Console.WriteLine("Bottles collected in room {0} = {1}", i + 1, rooms[i]);
}
//Outputs winner
Console.WriteLine("And the Winner is room " + maxRoomNumber + "!!!");
}
}
}
If you are not allowed to use arrays, you can declare 4 variables for all your array items.
int room1, room2, room3, room4;
I guess that's the intended approach to this exercise.
Here's an example that uses a Class to hold the information for each room. The reason for using a class is so that if your program needs to change in the future to collect more information, you won't have to track yet another array, you can just add properties to the class.
The individual rooms are now held in a list instead of an array just to show a different construct.
Here is the new Room class:
public class Room
{
public int Number { get; set; }
public int BottleCount { get; set; }
public Room(int wNumber)
{
Number = wNumber;
}
}
And here is the new version of the program. Note that additional checking of the values entered by the end user has been added in order to prevent exceptions when trying to get the current room or parse to an int the value entered by the user:
static void Main(string[] args)
{
const int MAX_ROOMS = 4;
var cRooms = new System.Collections.Generic.List<Room>();
for (int nI = 0; nI < MAX_ROOMS; nI++)
{
// The room number is 1 to 4
cRooms.Add(new Room(nI + 1));
}
// Initializes the room that wins
//Start of while loop to ask what room your adding into.
while (true)
{
Console.Write("Enter the room you're in: ");
//If user enters quit at anytime, the code will jump out of while statement and enter for loop below
string roomNumber = Console.ReadLine();
if (roomNumber == "quit")
{
//Break statement allows quit to jump out of loop
break;
}
int room = 0;
if (int.TryParse(roomNumber, out room) && (room < MAX_ROOMS) && (room >= 0)) {
Room currentRoom;
currentRoom = cRooms[room];
Console.Write("Bottles collected in room {0}: ", currentRoom.Number);
int wBottleCount = 0;
if (int.TryParse(Console.ReadLine(), out wBottleCount) && (wBottleCount >= 0))
{
// This line adds the count of bottles and records it so you can continuously count the bottles collected.
currentRoom.BottleCount += wBottleCount;
}
else
{
Console.WriteLine("Invalid bottle count; value must be greater than 0");
}
}
else
{
Console.WriteLine("Invalid room number; value must be between 1 and " + MAX_ROOMS.ToString());
}
}
Room maxRoom = null;
foreach (Room currentRoom in cRooms) //This loop goes through the array of rooms (4)
{
// This assumes that the bottle count can never be decreased in a room
if ((maxRoom == null) || (maxRoom.BottleCount < currentRoom.BottleCount))
{
maxRoom = currentRoom;
}
Console.WriteLine("Bottles collected in room {0} = {1}", currentRoom.Number, currentRoom.BottleCount);
}
//Outputs winner
Console.WriteLine("And the Winner is room " + maxRoom.Number + "!!!");
}

Categories