Doing a school activity but I hit a roadblock. I can't seem to make the program output the arrays I've entered. The output works when the variables inside the PlayerCharacter() and Mage() were all regular variables. Then I turned them into arrays because that was what was required of us, but then it started not showing anything during output.
using System;
namespace Summative
{
class PlayerCharacter
{
string[] name = new string[10];
int[] life = new int[10];
char[] gender = new char[10];
public int i = 0;
public int x = 0;
public PlayerCharacter()
{
Console.Write("Enter character name: ");
this.Name = Console.ReadLine();
Console.Write("Enter Life: ");
this.Life = int.Parse(Console.ReadLine());
Console.Write("Enter Gender (M/F): ");
this.Gender = char.Parse(Console.ReadLine());
i++;
}
public string Name
{
get
{
return name[i];
}
set
{
name[i] = value;
}
}
public int Life
{
get
{
return life[i];
}
set
{
life[i] = value;
}
}
public char Gender
{
get
{
return gender[i];
}
set
{
if (value == 'M' || value == 'F')
{
gender[i] = value;
}
else
{
Console.WriteLine("Invalid Gender!");
}
}
}
public virtual void Output()
{
Console.WriteLine("Name: " + string.Join(",", Name));
Console.WriteLine("Life: " + string.Join(",", Life));
Console.WriteLine("Gender: " + string.Join(",", Gender));
}
}
class Mage : PlayerCharacter
{
string[] element = new string[10];
int[] mana = new int[10];
public Mage() : base()
{
Console.Write("Enter element: ");
this.Elements = Console.ReadLine();
Console.Write("Enter mana: ");
this.Mana = int.Parse(Console.ReadLine());
}
public string Elements
{
get
{
return element[x];
}
set
{
element[x] = value;
}
}
public int Mana
{
get
{
return mana[x];
}
set
{
mana[x] = value;
}
}
public override void Output()
{
base.Output();
Console.WriteLine("Element: " + string.Join(",", Elements));
Console.WriteLine("Mana: " + string.Join(",", Mana));
x++;
}
}
class Rogue : PlayerCharacter
{
string faction;
float energy;
public Rogue() : base()
{
Console.Write("Enter faction name: ");
this.Faction = Console.ReadLine();
Console.Write("Enter energy: ");
this.Energy = float.Parse(Console.ReadLine());
}
public string Faction
{
get
{
return faction;
}
set
{
faction = value;
}
}
public float Energy
{
get
{
return energy;
}
set
{
energy = value;
}
}
public override void Output()
{
base.Output();
Console.WriteLine("Faction: " + Faction);
Console.WriteLine("Energy: " + Energy);
}
}
class Fighter : PlayerCharacter
{
string weapon;
double strength;
public Fighter() : base()
{
Console.Write("Enter weapon name: ");
this.Weapon = Console.ReadLine();
Console.Write("Enter strength: ");
this.Strength = double.Parse(Console.ReadLine());
}
public string Weapon
{
get
{
return weapon;
}
set
{
weapon = value;
}
}
public double Strength
{
get
{
return strength;
}
set
{
strength = value;
}
}
public override void Output()
{
base.Output();
Console.WriteLine("Weapon: " + Weapon);
Console.WriteLine("Strength: " + Strength);
}
}
class TestPlayer
{
static void Main(string[] args)
{
PlayerCharacter character;
CharacterCreator:
int switchchoice = 0;
Console.WriteLine("Select a class");
Console.WriteLine("1. Mage");
Console.WriteLine("2. Rogue");
Console.WriteLine("3. Fighter");
Console.WriteLine("0. Exit");
Console.Write("Enter Choice: ");
start:
try
{
switchchoice = int.Parse(Console.ReadLine());
}
catch
{
Console.Clear();
Console.WriteLine("Invalid Input! Please Try Again.");
goto CharacterCreator;
}
switch (switchchoice)
{
case 1:
Console.Clear();
character = new Mage();
character.Output();
break;
case 2:
Console.Clear();
character = new Rogue();
character.Output();
break;
case 3:
Console.Clear();
character = new Fighter();
character.Output();
break;
case 0:
Console.Clear();
goto start;
default:
Console.Clear();
Console.WriteLine("Invalid Input! Please Try Again.");
goto CharacterCreator;
}
int choice;
int y = 0;
int z;
int i = character.i;
int x = character.x;
Console.Clear();
Console.WriteLine("Player Character Designer");
Console.WriteLine("1. Create");
Console.WriteLine("2. View");
Console.Write("Enter Choice: ");
choice = int.Parse(Console.ReadLine());
if (choice == 1)
{
goto CharacterCreator;
}
else if (choice == 2)
{
z = i;
i = 0;
x = 0;
do
{
character.Output();
Console.WriteLine(" ");
y++;
i++;
x++;
} while (y != z);
}
}
}
}
Answer: Use a list
The main issue is that you should add the created characters in a list rather than keeping arrays of attributes inside characters. This lets you loop over each character and print all the information in turn. I.e.
var myCharacters = new List<PlayerCharacter>();
...
myCharacters.Add(myCharacter);
Other Issues
Constructors & object design
Inject parameters in constructors whenever possible, and use auto-properties when applicable. This helps avoid complex logic in the constructors, and reduces the size of the classes. Let the creator of the characters be responsible for reading the necessary parameters. I would also prefer to separate the construction of the information-string and the output, that way you can output the same information to a log file or whatever, and not just to the console. I.e:
class PlayerCharacter
{
public string Name { get; }
public int Life { get; }
public string Gender { get; }
public PlayerCharacter(string name, int life, string gender)
{
Name = name;
Life = life;
Gender = gender;
}
public override string ToString()
{
return $"Name: {Name}, Life {Life}, Gender: {Gender}";
}
}
Control flow
Use loops instead of goto. While I think there are cases where goto is the best solution, they are rare, and the general recommendation is to use loops for control flow i.e. something like this pseudocode
MyOptions option;
var myCharacters = new List<PlayerCharacter>();
do{
myCharacters.Add(ReadCharacter());
option = ReadOption();
}
while(option != MyOptions.ViewCharacters);
PrintCharacters(myCharacters);
Split code into methods
Move code into logical functions, especially for repeated code. This helps to make it easier to get a overview of the program. For example, for reading numbers it is better to use the TryParse function than trying to catch exceptions, and put it in a method to allow it to be reused:
int ReadInteger()
{
int value;
while (!int.TryParse(Console.ReadLine(), out value))
{
Console.WriteLine("Invalid Input! Please Try Again.");
}
return value;
}
Related
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed last year.
I have found nothing to answer this question, and I think it is different for my code. Probably because I am adding a custom object to an array, but I still don't know what is causing this. The error is on line 35. Code attached below.
using System;
class Player {
public string abilitySet;
public string name;
public void useAbility() {
if (abilitySet == "fire") {
Console.WriteLine(name + " used fireball which did 40 damage!");
}
}
}
class Match {
public int PlayerCount;
public Player[] players;
public void Start() {
Console.WriteLine("Game started! There are " + PlayerCount + " players!");
}
}
class Program {
public static void Main(string[] args) {
Match match = new Match();
Console.WriteLine("How many players are there?");
string playerCount = Console.ReadLine();
if (Int32.TryParse(playerCount, out int j)) {
Console.WriteLine("You have selected " + playerCount + " players!");
match.PlayerCount = j;
for (int i = 0; i < j; i++) {
Player plr = new Player();
match.players[i] = plr;
plr.name = "Player " + i;
Console.WriteLine("What do you want " + plr.name + "'s ability set to be?");
string ability = Console.ReadLine();
if (ability.ToLower() == "fire") {
Console.WriteLine(plr.name + " has " + ability + "!");
} else {
Console.WriteLine("That is not a ability!");
}
}
} else {
Console.WriteLine("Please enter a number of players not text!");
}
}
}
As #Backs mentioned, you are not initializing your variables. But I would organize your code as follows and use a List instead of an array. Much easier to read don't you think?
using System;
class Player
{
public Player(string name)
{
Name = name;
}
public string Name { get; set; } = String.Empty;
public string AbilitySet { get; set; } = String.Empty;
public void UseAbility()
{
if (AbilitySet == "fire")
{
Console.WriteLine(Name + " used fireball which did 40 damage!");
}
}
}
class Match
{
public List<Player> Players { get; set; } = new List<Player>();
public void Start()
{
Console.WriteLine("Game started! There are " + Players.Count + " players!");
}
}
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("How many players are there? Or type Q+ENTER to quit.");
int numberOfPlayers = 0;
while (true)
{
string input = Console.ReadLine();
if (input == "Q")
{
System.Environment.Exit(1);
}
if (!Int32.TryParse(input, out numberOfPlayers))
{
Console.WriteLine("Invalid input. Please enter a numeric value.");
continue;
}
if (numberOfPlayers <= 0)
{
Console.WriteLine("Number of players must be at least 1.");
continue;
}
break;
}
Match match = new Match();
for (int i = 0; i < numberOfPlayers; i++)
{
match.Players.Add(new Player($"Player {i + 1}"));
}
match.Start();
}
}
Field players of Match class is not initialized. You should create an array:
match.players = new Player[j];
Or do it in constructor:
class Match {
public int PlayerCount;
public Player[] players;
public Match(int count) {
PlayerCount = count;
players = new Player[count];
}
public void Start() {
Console.WriteLine("Game started! There are " + PlayerCount + " players!");
}
}
Match match = new Match(j);
First and foremost, I feel it necessary to mention that I am currently using replit for this program. The issue that I am currently having with my code is that it runs perfectly, the only issue is that when I try to backspace using the methods listed below and fix a number or letter that I have mistyped in my input while running the program, I get an error saying that the value must be positive and below the buffer height. I realized that the issue is some of my Console.ReadLine(); placements. They are causing my program to read backspace as an input and in turn, I am receiving an error because backspace is neither a letter or number input. Is there any way that I can move them around without having to rewrite the whole method line?
public static void AddItemToStore() {
Console.WriteLine("========= Adding Item to Store =========");
Console.WriteLine();
Console.WriteLine("You will need to enter an item description, price, and quantity on hand.");
Console.WriteLine();
Console.WriteLine("Please enter an item description:");
string input = Console.ReadLine();
double entry = GetPrice();
int value = GetQuantity();
itemDescription.Add(input);
itemPrice.Add(Convert.ToDouble(entry));
itemQoh.Add(value);
SaveData();
}
public static string GetCustomerName() {
Console.WriteLine();
Console.WriteLine("=========== List of Customers =========== ");
Console.WriteLine();
for (int i = 0; i < salesCustomerName.Count; i++) {
Console.WriteLine($"{i + 1}. {salesCustomerName[i]} ");
Console.WriteLine();
}
while (true) {
Console.WriteLine("Please choose a Customer name:");
Console.WriteLine();
return Console.ReadLine();
}
}
public static double GetPrice() {
while (true) {
Console.WriteLine();
Console.WriteLine("Enter the price of the item (x.xx):");
string entry = Console.ReadLine();
double value;
if (!double.TryParse(entry, out value) || value <= 0){
Console.WriteLine("Please enter a valid price value.");
} else {
return Convert.ToDouble(entry);
}
}
}
public static int GetQuantity() {
while (true){
Console.WriteLine();
Console.WriteLine("Please enter the item quantity:");
string entry = Console.ReadLine();
int value = 0;
if (Int32.TryParse(entry, out value) && Convert.ToInt32(entry) > 0){
return Convert.ToInt32(entry);
}
else{
Console.WriteLine("Please enter a valid value.");
}
}
}
Listed above are the methods that I am currently having an issue with. They work perfectly with inputting information but as soon as I press backspace, I get an error. Down below I will have my whole program listed as well.
using System;
using System.Collections.Generic;
using System.IO;
class Program {
public static List<string> itemDescription = new List<string>();
public static List<double> itemPrice = new List<double>();
public static List<int> itemQoh = new List<int>();
public static List<string> customerName = new List<string>();
public static List<string> salesCustomerName = new List<string>();
public static List<string> salesItemDescription = new List<string>();
public static List<double> salesItemPrice = new List<double>();
public static List<int> salesQuantity = new List<int>();
public static void Main (string[] args) {
ReadData();
bool keepGoing = true;
while (keepGoing) {
string entry = GetMenuOption();
if (entry.ToLower() == "q"){
Console.WriteLine("Thanks for shopping with us! Come back soon! :)");
}
switch (entry) {
case "1":
GoShopping();
break;
case "2":
Management();
break;
case "Q":
keepGoing = false;
break;
}
}
}
public static void AddItemToStore() {
Console.WriteLine("========= Adding Item to Store =========");
Console.WriteLine();
Console.WriteLine("You will need to enter an item description, price, and quantity on hand.");
Console.WriteLine();
Console.WriteLine("Please enter an item description:");
string input = Console.ReadLine();
double entry = GetPrice();
int value = GetQuantity();
itemDescription.Add(input);
itemPrice.Add(Convert.ToDouble(entry));
itemQoh.Add(value);
SaveData();
}
public static void AddItemToCart(string name, int item) {
Console.WriteLine();
Console.WriteLine($"There are {itemQoh[item]} {itemDescription[item]} available for {itemPrice[item]:C2} each.");
Console.WriteLine();
Console.WriteLine("Please choose the amount of items that you would like to purchase");
string val = Console.ReadLine();
int pur_qty =0;
int num = -1;
if (!int.TryParse(val, out num)) {
Console.WriteLine("Please enter a valid integer");
} else {
pur_qty = Convert.ToInt32(val);
if (pur_qty <= itemQoh[item] ){
itemQoh[item] = itemQoh[item]-pur_qty;
salesCustomerName.Add(name);
salesItemDescription.Add(itemDescription[item]);
salesItemPrice.Add(itemPrice[item]);
salesQuantity.Add(pur_qty);
SaveData();
}else{
Console.WriteLine();
Console.WriteLine("Please enter a valid value");
}
}
}
public static void ChangePrice() {
Console.WriteLine("========= Changing Price =========");
int entry = Convert.ToInt32(GetItemNumber());
int price = 0;
Console.WriteLine();
Console.WriteLine($"Updating price. {itemDescription[price]} currently costs {itemPrice[price]:C2}.");
double new_price = GetPrice();
itemPrice[entry]= new_price;
SaveItems();
SaveData();
}
public static void ChangeQoh() {
Console.WriteLine("========= Changing Quantity =========");
int entry = Convert.ToInt32(GetItemNumber());
int value = 0;
Console.WriteLine($"Updating quantity. There are currently {itemQoh[value]} {itemDescription[value]} available.");
Console.WriteLine();
int new_qty = GetQuantity();
itemQoh[entry]=new_qty;
SaveItems();
SaveData();
}
public static string GetCustomerName() {
Console.WriteLine();
Console.WriteLine("=========== List of Customers =========== ");
Console.WriteLine();
for (int i = 0; i < salesCustomerName.Count; i++) {
Console.WriteLine($"{i + 1}. {salesCustomerName[i]} ");
Console.WriteLine();
}
while (true) {
Console.WriteLine("Please choose a Customer name:");
Console.WriteLine();
return Console.ReadLine();
}
}
public static int GetItemNumber() {
ListAllItems();
int counter = itemDescription.Count;
string number;
int item = 1;
bool keepGoing = true;
while (keepGoing){
Console.WriteLine("Please enter an item number:");
number = Console.ReadLine();
item = Convert.ToInt32(number);
if (item < 1 || item > counter) {
Console.WriteLine();
Console.WriteLine($"Please enter a valid item number between 1 and {counter}.");
Console.WriteLine();
} else {
keepGoing = false;
}
}
return item -1;
}
public static string GetMenuOption() {
Console.WriteLine("=========== Main Menu ===========");
Console.WriteLine("1. Go Shopping");
Console.WriteLine("2. Management Menu");
Console.WriteLine("Q. Quit the program");
Console.WriteLine();
Console.Write("Please enter your choice: ");
return Console.ReadLine();
}
public static string GetManagementMenuOption() {
Console.WriteLine();
Console.WriteLine("=========== Management Menu =====");
Console.WriteLine("1. Browse sales receipts");
Console.WriteLine("2. View all items");
Console.WriteLine("3. Add an item");
Console.WriteLine("4. Change Quantity of Items on Hand");
Console.WriteLine("5. Change Prices of Items");
Console.WriteLine("Q. Return to Main Menu");
Console.WriteLine();
Console.Write("Please enter your choice: ");
return Console.ReadLine();
}
public static double GetPrice() {
while (true) {
Console.WriteLine();
Console.WriteLine("Enter the price of the item (x.xx):");
string entry = Console.ReadLine();
double value;
if (!double.TryParse(entry, out value) || value <= 0){
Console.WriteLine("Please enter a valid price value.");
} else {
return Convert.ToDouble(entry);
}
}
}
public static string GetShoppingOption() {
Console.WriteLine();
Console.WriteLine("=========== Shopping Menu ===========");
Console.WriteLine("1. Choose an item");
Console.WriteLine("Q. Checkout");
Console.WriteLine();
Console.Write("Please enter your choice: ");
return Console.ReadLine();
}
public static int GetQuantity() {
while (true){
Console.WriteLine();
Console.WriteLine("Please enter the item quantity:");
string entry = Console.ReadLine();
int value = 0;
if (Int32.TryParse(entry, out value) && Convert.ToInt32(entry) > 0){
return Convert.ToInt32(entry);
}
else{
Console.WriteLine("Please enter a valid value.");
}
}
}
private static void GoShopping() {
Console.WriteLine();
Console.WriteLine("Please enter the name of the shopper:");
while (true) {
string name = Console.ReadLine();
string entry = GetShoppingOption();
switch (entry) {
case "1" :
int item = GetItemNumber();
if (item != -1) {
AddItemToCart(name, item);
SaveData();
}
break;
case "Q" :
PrintTotalCart(name);
return;
}
}
}
public static void ListAllItems() {
Console.WriteLine();
Console.WriteLine("============== All Items ============= ");
for (int i = 0; i < itemDescription.Count; i++) {
Console.WriteLine($"{i + 1}. {itemDescription[i]} costs {itemPrice[i]:C2}. There are {itemQoh[i]} available.");
Console.WriteLine();
}
}
public static void Management() {
while (true) {
string entry = GetManagementMenuOption();
if (entry.ToLower() == "q") {
return;
} else {
switch (entry) {
case "1" :
string customer = GetCustomerName();
PrintTotalCart(customer);
break;
case "2" :
ListAllItems();
break;
case "3" :
AddItemToStore();
break;
case "4" :
ChangeQoh();
break;
case "5" :
ChangePrice();
break;
default:
Console.WriteLine("Please make a valid selection");
break;
}
}
}
}
public static void PrintTotalCart(string name) {
Console.WriteLine();
Console.WriteLine($"======= All Purchases for {name} =======" );
double total_cost= 0;
for (int i = 0; i < salesCustomerName.Count; i++) {
if(salesCustomerName[i] == name) {
total_cost += salesQuantity[i] *salesItemPrice[i];
Console.WriteLine($"{salesQuantity[i]} {salesItemDescription[i]} at the price of {salesItemPrice[i]:C2} each for a total of {salesQuantity[i] *salesItemPrice[i]:C2}.");
}
}
Console.WriteLine();
Console.WriteLine($"Total cost of the cart for {name} is {total_cost:C2}.");
}
public static void ReadData() {
ReadItems();
ReadSales();
}
public static void ReadItems() {
var filename = "items.csv";
if (File.Exists(filename)) {
using (var reader = new StreamReader(filename)) {
reader.ReadLine();
while (!reader.EndOfStream) {
var line = reader.ReadLine();
var values = line.Split(",");
itemDescription.Add(values[0]);
itemPrice.Add(Convert.ToDouble(values[1]));
itemQoh.Add(Convert.ToInt32(values[2]));
}
}
}else {
Console.WriteLine($"{filename} not found");
}
}
public static void ReadSales() {
var filename = "sales.csv";
if (File.Exists(filename)) {
using (var reader = new StreamReader(filename)) {
reader.ReadLine();
while (!reader.EndOfStream) {
var line = reader.ReadLine();
var values = line.Split(",");
salesCustomerName.Add(values[0]);
salesItemDescription.Add(values[1]);
salesItemPrice.Add(Convert.ToDouble(values[2]));
salesQuantity.Add(Convert.ToInt32(values[3]));
}
}
}else {
Console.WriteLine($"{filename} not found");
}
}
public static void SaveData() {
SaveItems();
SaveSales();
}
public static void SaveItems() {
string filename = "items.csv";
using (var writer = new StreamWriter(filename)) {
writer.WriteLine("Item_Description,Item_Price,Qoh");
for (int i = 0; i < itemDescription.Count; i++) {
writer.WriteLine($"{itemDescription[i]},{itemPrice[i]},{itemQoh[i]}");
}
}
}
public static void SaveSales() {
string filename = "sales.csv";
using (var writer = new StreamWriter(filename)) {
writer.WriteLine("Customer_Name,Item_Description,Item_Price,Sales_Qty");
for (int i = 0; i < salesCustomerName.Count; i++) {
writer.WriteLine($"{salesCustomerName[i]},{salesItemDescription[i]},{salesItemPrice[i]},{salesQuantity[i]}");
}
}
}
}
This is the error that I receive each time that I enter the backspace.
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.
i have a menu.Basically, i need to fix this error. I had it working fine, until now. With the Console.Clear on, I can ONLY use 1 or 8. 2-7 just clears out.It SHOULD display "You need to create a student first". If I turn Console.Clear off, then it works. However, I need it on since that is the part that resets the menu. Plus it also runs the line that is only supposed to run when you exit. I didn't change anything major.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GradeCalculator
{
class Program
{
static void Main(string[] args)
{
Student currentStudent = null;
bool running = true; // Logic 1
string input = "";
while(running)
{
// display menu
Console.Clear();
Console.WriteLine("Main menu: ");
Console.WriteLine("1. Create a student");
Console.WriteLine("2. Add a course to the current student");
Console.WriteLine("3. Remove a course from the current student");
Console.WriteLine("4. Add grades for a course");
Console.WriteLine("5. Display student info");
Console.WriteLine("6. Display grades for a course");
Console.WriteLine("7. Display all grades");
Console.WriteLine("8. Exit");
Console.Write("Enter a selection: (1 - 8): ");
input = Console.ReadLine().ToLower();
Console.WriteLine();
// handle choices
//------------------------------------------------------------------------
switch(input)
{
case "1":
case "create a student":
{
Console.Write("What is the students first name? ");
string firstName = Console.ReadLine();
Console.Write("What is the students last name? ");
string lastName = Console.ReadLine();
currentStudent = new Student(firstName, lastName);
Console.Write("How old is the student? ");
string studentAge = Console.ReadLine(); // Logic 2
int age;
while(!int.TryParse(studentAge, out age))
{
Console.Write("Please enter a number: ");
studentAge = Console.ReadLine();
}
currentStudent.Age = age;
Console.Write("What is the students address? ");
currentStudent.Address = Console.ReadLine();
Console.Write("What is the students email? ");
currentStudent.Email = Console.ReadLine();
Console.Write("What is the students phone number? ");
currentStudent.Phone = Console.ReadLine();
}
break;
case "2":
case "add a course to the current student":
{
if(currentStudent != null)
{
currentStudent.AddACourse();
}
else
{
Console.WriteLine("Please create a student first.");
}
}
break;
case "3":
case "remove a course from the current student":
{
if (currentStudent != null)
{
currentStudent.RemoveACourse();
}
else
{
Console.WriteLine("Please create a student first.");
}
}
break;
case "4":
case "add grades for a course":
{
if (currentStudent != null)
{
currentStudent.AddGradesForACourse();
}
else
{
Console.WriteLine("Please create a student first.");
}
}
break;
case "5":
case "display student info":
{
if (currentStudent != null)
{
currentStudent.DisplayInfo();
}
else
{
Console.WriteLine("Please create a student first.");
}
}
break;
case "6":
case "display grades for a course":
{
if (currentStudent != null)
{
currentStudent.DisplayGradesForACourse();
}
else
{
Console.WriteLine("Please create a student first.");
}
}
break;
case "7":
case "display all grades":
{
if (currentStudent != null)
{
currentStudent.DisplayAllGrades();
}
else
{
Console.WriteLine("Please create a student first.");
}
}
break;
case "8":
case "exit":
{
running = false; // Logic 6
}
break;
default:
return;
}
Console.WriteLine("You have chosen to exit");
//Console.ReadKey();
}
}
}
}
Student Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GradeCalculator
{
class Student
{
static int _nextStudentIDNum = 1000;
string _firstName;
string _lastName;
string _email;
string _address;
string _phoneNumber;
int _age;
int _studentIdNum;
List<Course> _courses;
public Student(string firstName, string lastName)
{
_firstName = firstName;
_lastName = lastName;
_studentIdNum = ++_nextStudentIDNum;
_courses = new List<Course>();
}
public string Name
{
get
{
return $"{_lastName}, {_firstName}";
}
}
public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
}
}
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
}
}
public string Address
{
get
{
return _address;
}
set
{
_address = value;
}
}
public string Email
{
get
{
return _email;
}
set
{
_email = value;
}
}
public string Phone
{
get
{
return _phoneNumber;
}
set
{
_phoneNumber = value;
}
}
public int Age
{
get
{
return _age;
}
set
{
_age = value;
}
}
public int StudentNumber
{
get
{
return _studentIdNum;
}
set
{
_studentIdNum = value;
}
}
public List<Course> Courses
{
get
{
return _courses;
}
}
private int SelectCourse(string message)
{
int len = _courses.Count;
int index = -1;
if (len > 0) //Logic 3
{
for (index = 0; index < len; ++index)
{
Console.WriteLine($"{index + 1}. {_courses[index].Title}");
}
Console.Write(message);
string selection = Console.ReadLine();
while (!int.TryParse(selection, out index) || (index < 1 || index > len))
{
Console.Write("Please make a valid selection: ");
selection = Console.ReadLine();
}
--index;
}
return index;
}
public void AddACourse()
{
string input;
Console.Write("How many assignments are in the course? ");
input = Console.ReadLine();
int numAssignments = 0;
while (!int.TryParse(input, out numAssignments))
{
Console.Write("Please enter a number: ");
input = Console.ReadLine();
}
Course course = new Course(numAssignments);
Console.Write("What is the courses title? ");
course.Title = Console.ReadLine();
Console.Write("What is the courses description? ");
course.Description = Console.ReadLine();
_courses.Add(course);
}
public void RemoveACourse()
{
int index = SelectCourse("Select a course to remove. (Enter the number): ");
if (index == -1) //Logic 8
{
Console.WriteLine("No courses to remove. Try adding one first.");
}
else
{
_courses.RemoveAt(index);
}
}
public void AddGradesForACourse()
{
int index = SelectCourse("Select a course to add grades for. (Enter the number): ");
if (index == -1)
{
Console.WriteLine("No course to add grades to. Try adding one first.");
}
else
{
_courses[index].AddGrades();
}
}
public void DisplayGradesForACourse()
{
int index = SelectCourse("Select a course to display grades for. (Enter the number): ");
if (index == -1)
{
Console.WriteLine("No course to display grades for. Try adding one first.");
}
else
{
_courses[index].DisplayGrades();
}
}
public void DisplayAllGrades()
{
foreach (Course c in _courses)
{
c.DisplayGrades(); //Logic 7
}
}
public void DisplayInfo()
{
Console.WriteLine($"Name: {Name}\nAge: {Age}\nAddress: {Address}\nPhone: {Phone}\nEmail: {Email}");
}
}
}
Course Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GradeCalculator
{
class Course
{
string _title;
string _description;
Grade[] _grades;
int _graded;
public string Title
{
get
{
return _title;
}
set
{
_title = value;
}
}
public string Description
{
get
{
return _description;
}
set
{
_description = value;
}
}
public Grade[] Grades
{
get
{
return _grades;
}
}
public Course(int numberOfAssignments)
{
_grades = new Grade[numberOfAssignments];
_graded = 32;
}
public void AddGrades()
{
do
{
for (int i = 0; i < _grades.Length; ++i)
{
_grades[i] = new Grade();
Console.Write($"Enter a description for assignment {i + 1}: ");
_grades[i].Description = Console.ReadLine();
string input;
float value;
Console.Write($"Enter the grade earned for assignment {i + 1} as a percentage (0 - 100): ");
input = Console.ReadLine();
while (!float.TryParse(input, out value)) // Logic 4
{
Console.WriteLine("Please enter a number: ");
input = Console.ReadLine();
}
_grades[i].PercentEarned = value;
Console.Write($"Enter assignment {i + 1}'s weight of total grade as a percentage (0 - 100): ");
input = Console.ReadLine();
while (!float.TryParse(input, out value))
{
Console.WriteLine("Please enter a number: ");
input = Console.ReadLine();
}
_grades[i].Weight = value;
}
}
while (ValidateWeightTotal() == false);
_graded = 0;
}
private bool ValidateWeightTotal()
{
float precisionFactor = 0.001f;
float _totalWeight = 0;
bool result = false;
for (int i = 0; i < _grades.Length; ++i)
{
_totalWeight += _grades[i].Weight;
}
if(_totalWeight < 100 + precisionFactor && _totalWeight > 100 - precisionFactor)
{
result = true;
}
if (result == false)
{
Console.WriteLine($"Weight total = {_totalWeight} instead of 100.\nPlease enter the values again.\n");
}
return result;
}
public float GetFinalGrade()
{
bool weightsAreValid = ValidateWeightTotal();
float finalGrade = 0;
if(weightsAreValid)
{
for (int i = 0; i < _grades.Length; ++i)
{
finalGrade += _grades[i].GetPercentOfFinalGrade();
}
}
return finalGrade;
}
public void DisplayGrades()
{
if (_graded == 0)
{
float total = 0f;
Console.WriteLine("-------------------------------------");
Console.WriteLine($"Title: {Title}");
for (int i = 0; i < _grades.Length; ++i)
{
Grade grade = _grades[i];
total += grade.GetPercentOfFinalGrade();
Console.WriteLine($"Desc: {grade.Description}\nEarned: {grade.PercentEarned}\nPercent towards final grade: {grade.GetPercentOfFinalGrade()}\n");
}
Console.WriteLine($"Grade for the course: {total}");
Console.WriteLine("-------------------------------------");
}
else
{
Console.WriteLine("Please add grades first.");
}
}
}
}
Grade Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GradeCalculator
{
class Grade
{
string _description;
float _percentEarned;
float _weight;
public string Description
{
get
{
return _description;
}
set
{
_description = value;
}
}
public float PercentEarned
{
get
{
return _percentEarned;
}
set
{
_percentEarned = value;
if (value < 0.0f || value > 100.0f)
{
//_percentEarned = 0;
Console.WriteLine("Percent earned was less than 0 or greater than 100 so value was set to 0.");
}
else
{
_percentEarned = value;
}
}
}
public float Weight
{
get
{
return _weight;
}
set
{
if (value < 0.0f || value > 100.0f)
{
//_weight = 0;
Console.WriteLine("Weight was less than 0 or greater than 100 so value was set to 0.");
}
else
{
_weight = value;
}
}
}
public float GetPercentOfFinalGrade()
{
float result = (_percentEarned * _weight) / 100;
return result;
}
}
}
all you need is to clear the console at the End of the Loop and make it Stay there for a While just to show user the output you would do something like this
i have Added like , 3000 means for 3000 milliseconds that are 3 seconds we will show the user error and then we will clear the output and show the menu again,use 3 seconds or 5 seconds(5000),what ever you want, and then clear the output
System.Threading.Thread.Sleep(3000);
Console.Clear();
static void Main(string[] args)
{
Student currentStudent = null;
bool running = true; // Logic 1
string input = "";
while (running)
{
// display menu
Console.WriteLine("Main menu: ");
Console.WriteLine("1. Create a student");
Console.WriteLine("2. Add a course to the current student");
Console.WriteLine("3. Remove a course from the current student");
Console.WriteLine("4. Add grades for a course");
Console.WriteLine("5. Display student info");
Console.WriteLine("6. Display grades for a course");
Console.WriteLine("7. Display all grades");
Console.WriteLine("8. Exit");
Console.Write("Enter a selection: (1 - 8): ");
input = Console.ReadLine().ToLower();
Console.WriteLine();
// handle choices
//------------------------------------------------------------------------
switch (input)
{
case "1":
case "create a student":
{
Console.Write("What is the students first name? ");
string firstName = Console.ReadLine();
Console.Write("What is the students last name? ");
string lastName = Console.ReadLine();
currentStudent = new Student(firstName, lastName);
Console.Write("How old is the student? ");
string studentAge = Console.ReadLine(); // Logic 2
int age;
while (!int.TryParse(studentAge, out age))
{
Console.Write("Please enter a number: ");
studentAge = Console.ReadLine();
}
currentStudent.Age = age;
Console.Write("What is the students address? ");
currentStudent.Address = Console.ReadLine();
Console.Write("What is the students email? ");
currentStudent.Email = Console.ReadLine();
Console.Write("What is the students phone number? ");
currentStudent.Phone = Console.ReadLine();
}
break;
case "2":
case "add a course to the current student":
{
if (currentStudent != null)
{
currentStudent.AddACourse();
}
else
{
Console.WriteLine("Please create a student first.");
}
}
break;
case "3":
case "remove a course from the current student":
{
if (currentStudent != null)
{
currentStudent.RemoveACourse();
}
else
{
Console.WriteLine("Please create a student first.");
}
}
break;
case "4":
case "add grades for a course":
{
if (currentStudent != null)
{
currentStudent.AddGradesForACourse();
}
else
{
Console.WriteLine("Please create a student first.");
}
}
break;
case "5":
case "display student info":
{
if (currentStudent != null)
{
currentStudent.DisplayInfo();
}
else
{
Console.WriteLine("Please create a student first.");
}
}
break;
case "6":
case "display grades for a course":
{
if (currentStudent != null)
{
currentStudent.DisplayGradesForACourse();
}
else
{
Console.WriteLine("Please create a student first.");
}
}
break;
case "7":
case "display all grades":
{
if (currentStudent != null)
{
currentStudent.DisplayAllGrades();
}
else
{
Console.WriteLine("Please create a student first.");
}
}
break;
case "8":
case "exit":
{
running = false; // Logic 6
}
break;
default:
return;
}
Console.WriteLine("You have chosen to exit");
//Console.ReadKey();
System.Threading.Thread.Sleep(3000);
Console.Clear();
}
}
I am having a problem getting my program to check the input previous and compare it so the user cannot duplicate an order number. Right now the program will run all the way through and look the way I want, but it accepts duplicate order numbers while I would like it to inform the user and ask them to reenter. The problem seems to be that my check[y] array does not contain any value when I compare it. How do I get this array to contain the previously entered order numbers so it will display the error message. I am just going to post the entire code so you can see what I have done so far. Others have suggested the List type, but I am a student and have not learned this yet. I believe I am supposed to use the Equals method. Any help would be appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Assignment6_Hergott
{
class Order : IComparable <Order>
{
public int orderNumber { get; set; }
public string customerName { get; set; }
public int quanityOrdered { get; set; }
public double total;
public const double priceEach = 19.95;
public Order()
{
}
public Order(int number, string name, int quanity)
{
number = orderNumber;
name = customerName;
quanity = quanityOrdered;
}
public double totalPrice
{
get
{
return total;
}
}
public int CompareTo(Order o)
{
return this.orderNumber.CompareTo(o.orderNumber);
}
public override bool Equals(Object e)
{
bool equal;
Order temp = (Order)e;
if (orderNumber == temp.orderNumber)
equal = true;
else
equal = false;
return equal;
}
public override int GetHashCode()
{
return Convert.ToInt32(orderNumber);
}
public override string ToString()
{
return "ShippedOrder " + orderNumber + " " + customerName + " " + quanityOrdered +
" # " + priceEach + " each.";
}
}
class ShippedOrder : Order
{
public const int shippingFee = 4;
public override string ToString()
{
return base.ToString() + " Shipping is " + shippingFee + " Total is " + totalPrice;
}
}
class Program
{
static void Main(string[] args)
{
double sum = 0;
ShippedOrder[] orderArray = new ShippedOrder[5];
ShippedOrder[] check = new ShippedOrder[5];
bool wrong = true;
for (int x = 0; x < orderArray.Length; ++x)
{
orderArray[x] = new ShippedOrder();
Console.Write("Enter order number: ");
orderArray[x].orderNumber = Convert.ToInt32(Console.ReadLine());
for (int y = 0; y < x; y++)
{
check[y] = new ShippedOrder();
if (orderArray[x].Equals(check[y]))
wrong = false;
while (!wrong)
{
Console.WriteLine("Sorry, the order number {0} is a duplicate.
\nPlease reenter: ", orderArray[x].orderNumber);
for (y = 0; y < x; y++)
{
if (orderArray[x].Equals(check[y]))
wrong = false;
}
check[y] = orderArray[x];
}
}
Console.Write("Enter cusomer name: ");
orderArray[x].customerName = Console.ReadLine();
Console.Write("Enter quanity: ");
orderArray[x].quanityOrdered = Convert.ToInt32(Console.ReadLine());
orderArray[x].total = orderArray[x].quanityOrdered * Order.priceEach +
ShippedOrder.shippingFee;
sum += orderArray[x].total;
}
Array.Sort(orderArray);
for (int x = 0; x < orderArray.Length; x++)
{
Console.WriteLine(orderArray[x].ToString());
}
Console.WriteLine();
Console.WriteLine("Total for all orders is {0:c} ", sum);
}
}
}
I had a few minutes so I changed my answer to show you one way it could be done. If you just copy/paste this you'll be doing yourself a disservice, though (and your instructor will probably be able to tell). Take a look at the solution and see how it differs from yours. I hesitated to post a full solution but I thought this might be an okay way for you to figure out what you'd done wrong.
namespace ConsoleApplication2
{
using System;
using System.Linq;
public class Order : IComparable<Order>
{
public const double PriceEach = 19.95;
public Order()
{
}
public Order(int number, string name, int quanity)
{
this.OrderNumber = number;
this.CustomerName = name;
this.QuanityOrdered = quanity;
}
public int OrderNumber { get; set; }
public string CustomerName { get; set; }
public int QuanityOrdered { get; set; }
public int CompareTo(Order o)
{
return this.OrderNumber.CompareTo(o.OrderNumber);
}
public override bool Equals(object e)
{
int compareTo;
int.TryParse(e.ToString(), out compareTo);
return this.OrderNumber == compareTo;
}
public override int GetHashCode()
{
return Convert.ToInt32(this.OrderNumber);
}
public override string ToString()
{
return "Shipped order number " + this.OrderNumber + " for customer " + this.CustomerName + " " + this.QuanityOrdered +
" # $" + PriceEach + " each.";
}
}
public class ShippedOrder : Order
{
public const int ShippingFee = 4;
public double TotalPrice
{
get
{
return (this.QuanityOrdered * PriceEach) + ShippingFee;
}
}
public override string ToString()
{
return base.ToString() + " Shipping is $" + ShippingFee + ". Total is $" + this.TotalPrice;
}
}
public class Program
{
private static readonly int[] OrderNumbers = new int[5];
private static readonly ShippedOrder[] ShippedOrders = new ShippedOrder[5];
public static void Main(string[] args)
{
double sum = 0;
for (var i = 0; i < OrderNumbers.Length; i++)
{
OrderNumbers[i] = InputOrderNumber();
var name = InputCustomerName();
var quantity = InputQuantity();
ShippedOrders[i] = new ShippedOrder { CustomerName = name, QuanityOrdered = quantity, OrderNumber = OrderNumbers[i] };
sum += ShippedOrders[i].TotalPrice;
}
Array.Sort(ShippedOrders);
foreach (var t in ShippedOrders)
{
Console.WriteLine(t.ToString());
}
Console.WriteLine();
Console.WriteLine("Total for all orders is {0:c} ", sum);
Console.WriteLine();
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
}
private static int InputOrderNumber()
{
Console.Write("Enter order number: ");
var parsedOrderNumber = InputNumber();
if (ShippedOrders.Any(shippedOrder => shippedOrder != null && shippedOrder.OrderNumber.Equals(parsedOrderNumber)))
{
Console.WriteLine("Order number {0} is a duplicate.", parsedOrderNumber);
return InputOrderNumber();
}
return parsedOrderNumber;
}
private static string InputCustomerName()
{
Console.Write("Enter customer name: ");
var customerName = Console.ReadLine();
if (customerName == null || string.IsNullOrEmpty(customerName.Trim()))
{
Console.WriteLine("Customer name may not be blank.");
return InputCustomerName();
}
return customerName;
}
private static int InputQuantity()
{
Console.Write("Enter quantity: ");
return InputNumber();
}
private static int InputNumber()
{
int parsedInput;
var input = Console.ReadLine();
if (!int.TryParse(input, out parsedInput))
{
Console.WriteLine("Enter a valid number.");
return InputNumber();
}
return parsedInput;
}
}
}
my check[y] array does not contain any value when I compare it. How do
I get this array to contain the previously entered order numbers
If you want check[] to contain order numbers, it needs to be of the type of order number (an int, in this case). So whenever you add a new order to the orderArray, also add its number to the check array. Then you can test against earlier numbers.
If this doesn't solve your problem, add a follow-up question as a comment telling us what you tried and we can go from there.