I need to get my console output to a text file also. How can this be possible with the following code? I hope that a routined person can help me out :-)
namespace MyProject
{
// Creating a class for salesmen
class Person
{
// Variables for the salesmen
public string name;
public long personNumber;
public string district;
public int soldArticles;
// Constructor for the class
public Person(string name, long personNumber, string district, int soldArticles)
{
this.name = name;
this.personNumber = personNumber;
this.district = district;
this.soldArticles = soldArticles;
}
// Method to read input from user about the salesmen
public static Person ReadSeller()
{
Console.Write("\nEnter name of the salesman: ");
string name = Console.ReadLine();
Console.Write("\nPlease enter person number: ");
long personNumber = long.Parse(Console.ReadLine());
Console.Write("\nPlease enter what district you operate in: ");
string district = Console.ReadLine();
Console.Write("\nPlease enter amount of sold articles: ");
int soldArticles = int.Parse(Console.ReadLine());
return new Person(name, personNumber, district, soldArticles);
}
}
class Program
{
static void Main(string[] args)
{
// prompt user to enter how many salesmen there are in the salesforce
Console.Write("\nHow many salesmen are you in the salesforce? ");
int numOfSalesmen = int.Parse(Console.ReadLine());
// List that holds the salesmen
List<Person> sellers = new List<Person>();
// for loop that will iterate through the given amount of salesmen
for (int i = 1; i <= numOfSalesmen; i++)
{
Console.WriteLine("\nPlease fill in data for salesman {0}", i);
sellers.Add(Person.ReadSeller());
Console.WriteLine("--------------------------------------------------");
}
// sort the list with bubblesort
SortByBubblesort(sellers);
// print the salesmen
PrintSalesmen(sellers);
}
// This method sorts the List Person with the bubblesort method from least to most sold articles.
static List<Person> SortByBubblesort(List<Person> sellers)
{
int timesNumbersChanged;
do
{
timesNumbersChanged = 0;
for (int i = 0; i < sellers.Count - 1; i++)
{
if (sellers[i].soldArticles > sellers[i + 1].soldArticles)
{
Person salesman = sellers[i];
sellers.RemoveAt(i);
sellers.Insert(i + 1, salesman);
timesNumbersChanged += 1;
}
}
} while (timesNumbersChanged != 0);
return sellers;
}
// This method prints the salesmen in the order of what level they belong to.
static List<Person> PrintSalesmen(List<Person> sellers)
{
// Constants & variables
const int LEVEL_ONE = 50;
const int LEVEL_TWO = 99;
const int LEVEL_THREE = 199;
const int LEVEL_FOUR = 200;
int count = 0;
// headline for the output
Console.WriteLine("{0,-20} {1,-20} {2,-10} {3,-10}", "Name", "Person number", "District", "Articles sold");
// Counts how many salesmen that belongs to level 1
foreach (Person salesman in sellers)
{
if (salesman.soldArticles < LEVEL_ONE)
{
count++;
Console.Write("\n{0,-20} {1,-20} {2,-10} {3,-10}", salesman.name, salesman.personNumber, salesman.district, salesman.soldArticles);
}
}
// bottomline for level 1.
Console.WriteLine("\n" + count + " Salesmen reached level 1: Under 50 articles");
// Counts how many salesmen that belong to level 2
count = 0;
foreach (Person salesman in sellers)
{
if (salesman.soldArticles >= LEVEL_ONE && salesman.soldArticles <= LEVEL_TWO)
{
count++;
Console.Write("\n{0,-20} {1,-20} {2,-10} {3,-10}", salesman.name, salesman.personNumber, salesman.district, salesman.soldArticles);
}
}
// bottomline for level 2.
Console.WriteLine("\n" + count + " Salesmen reached level 2: 50-99 articles");
// Counts how many salesmen that belongs to level 3
count = 0;
foreach (Person salesman in sellers)
{
if (salesman.soldArticles > LEVEL_TWO && salesman.soldArticles <= LEVEL_THREE)
{
count++;
Console.Write("\n{0,-20} {1,-20} {2,-10} {3,-10}", salesman.name, salesman.personNumber, salesman.district, salesman.soldArticles);
}
}
// bottomline for level 3.
Console.WriteLine("\n" + count + " Salesmen reached level 3: 100-199 articles");
// Counts how many salesmen that belongs to level 4
count = 0;
foreach (Person salesman in sellers)
{
if (salesman.soldArticles >= LEVEL_FOUR)
{
count++;
Console.Write("\n{0,-20} {1,-20} {2,-10} {3,-10}", salesman.name, salesman.personNumber, salesman.district, salesman.soldArticles);
}
}
// bottomline for level 4.
Console.WriteLine("\n" + count + " Salesmen reached level 4: Over 199 articles");
return sellers;
}
}
}
Use Console.SetOut(...)
https://learn.microsoft.com/en-us/dotnet/api/system.console.setout?view=net-6.0.
In general I would suggest to replace Console with an logging framework. e.g. Log4Net:
https://stackify.com/log4net-guide-dotnet-logging/
Related
I am trying to print product details by creating a class Product and a method Display() in Product class to display product details.
I created an array of Product and trying to save products in array and trying to display the products from array by using Display Method.
User should provide choice whether he wants to ADD PRODUCT , DISPLAY PRODUCT or EXIT
based on choice need to perform action.
class Product
{
private static int m_intProductCounter = 0; // Initially Making Product Count = 0
public Product() // Constructor for class Product
{
m_intProductCounter++; // Whenever new object is created or Constructor is called Count Increases
}
public int ProductCount // Properity for Product Count
{
get { return m_intProductCounter; }
}
private int m_intProductid; // Product Id Variable
public int ProductId // properity for Product Id
{
get { return m_intProductid; }
set
{
if (value > 0)
m_intProductid = value;
else
throw new Exception("Invalid Product Id! Please Check Product Id.");
}
}
private string m_strProductName; // Product Name Variable
public string ProductName // Properity for Product Name
{
get { return m_strProductName; }
set
{
if (value.Length > 3)
m_strProductName = value;
else
throw new Exception("Invalid Product Name! Please Check Product Name.");
}
}
private DateTime m_dateManufacturedDate = DateTime.UtcNow; // Product Manufactured date variable
//private DateTime m_dateExpiryDate;
public DateTime ExpiryDate // Product Expiry Date Calculation
{
get { return m_dateManufacturedDate.AddYears(2); }
}
private int m_intProductQuantity; // Product Quantity variable
public int ProductQnty
{
get { return m_intProductQuantity; } // Properity for Product Quantity
set
{
if (value > 0 && value <= 500)
m_intProductQuantity = value;
else if (value < 0)
throw new Exception("Invalid Quantity! Product Quantity cannot be Less Than 0");
else
throw new Exception("Invalid Quantity! Product Quantity Cannot be more than 500.");
}
}
private decimal m_decProductPrice; // Product Price variable
public decimal ProductPrice // Properity for Product Price
{
get { return m_decProductPrice; }
set
{
if (value > 0)
m_decProductPrice = value;
else
throw new Exception("Invalid Producr Price! Product price Cannot Be less than 0");
}
}
private decimal m_decDiscountPrice; // Product Discount variable
public decimal Discount // Properity for Product Discount
{
get { return m_decDiscountPrice; }
set
{
if (value <= 45 && value > 0)
m_decDiscountPrice = value;
else if (value < 0)
throw new Exception("Product Discount can be either 0 or morethan that, but can't be zero.");
else
throw new Exception("Product discount can't be more than 45");
}
}
public string Display() // Displaying Product Details.
{
StringBuilder display = new StringBuilder();
display.Append("Product ID = " + ProductId + "\n");
display.Append("Product Name = " + ProductName + "\n");
//disp.Append("Product Manufactured Date = " + );
display.Append("Product Expiry Date = " + ExpiryDate + "\n");
display.Append("Product Price Per 1 Quantity = " + ProductPrice + "\n");
display.Append("Product Quantity = " + ProductQnty + "\n");
display.Append("Product Discount per 1 Quantity= " + Discount + "\n");
return display.ToString();
}
}
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Enter 1 to ADD product.\n Enter 2 to Display Product. \n Enter 3 to Exit.");
string Instruction = Console.ReadLine();
Product[] products = new Product[3];
switch (Instruction)
{
case "1":
{
Product p1 = new Product();
Console.Write("Enter Producr Id : ");
p1.ProductId = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Product Name : ");
p1.ProductName = Console.ReadLine();
Console.Write("Enter Product Quantity : ");
p1.ProductQnty = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Product Price : ");
p1.ProductPrice = Convert.ToDecimal(Console.ReadLine());
Console.Write("Enter Product Discount in number without % symbol : ");
p1.Discount = Convert.ToDecimal(Console.ReadLine());
products.Append(p1);
Console.WriteLine("\n \n \n" + "Product Added Succesfully \n " + "ThankYou.");
Console.WriteLine("Total Products Entered = " + p1.ProductCount);
}
break;
case "2":
{
Console.WriteLine(products[0].Display());
break;
}
}
if (Instruction == "3")
break;
}
}
}
why you are using array for products collection? And inside while you are always creating new array for products (inside while: Product[] products = new Product[3];)!
Use List or any dynamic collection in this case, change your main method to this:
static void Main(string[] args)
{
var products = new List<Product>();
while (true)
{
Console.WriteLine("Enter 1 to ADD product.\n Enter 2 to Display Product. \n Enter 3 to Exit.");
string Instruction = Console.ReadLine();
switch (Instruction)
{
case "1":
{
var p1 = new Product();
Console.Write("Enter Producr Id : ");
p1.ProductId = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Product Name : ");
p1.ProductName = Console.ReadLine();
Console.Write("Enter Product Quantity : ");
p1.ProductQnty = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Product Price : ");
p1.ProductPrice = Convert.ToDecimal(Console.ReadLine());
Console.Write("Enter Product Discount in number without % symbol : ");
p1.Discount = Convert.ToDecimal(Console.ReadLine());
products.Add(p1);
Console.WriteLine("\n \n \n" + "Product Added Succesfully \n " + "ThankYou.");
Console.WriteLine("Total Products Entered = " + p1.ProductCount);
}
break;
case "2":
{
foreach (var item in products)
Console.WriteLine(item.Display());
break;
}
}
if (Instruction == "3")
break;
}
}
i am trying to give the user 2 options one is to see what the array stored, and the second option is to enter the new items. Any help please! I have tried to add the array in the method ItemInfo() but it doesn't work as well, i have tried to do like this in switch:
ItemInfo(itemNArr[itemN],itemNameArr[itemName],itemPriceArr[itemPrice],itemStockArr[itemNStock],itemRatingArr[itemRating]
but still does not work as well. So what i should do in this case to pass the user input to the array and store it!? I will appreciate the help.
The problem that i got is:
The name 'itemN' does not exist in the current context line 37
The name 'itemName' does not exist in the current context line 37
The name 'itemPrice' does not exist in the current context line 37
The name 'itemNStock' does not exist in the current context line 37
The name 'itemRating' does not exist in the current context line 37
And the code is here:
using System;
using System.Security.Cryptography.X509Certificates;
using static System.Console;
namespace program
{
class UseItem
{
public static void Main(string[] args)
{
int item = AppIntro();
string[] itemNArr = new string[item];
string[] itemNameArr = new string[item];
double[] itemPriceArr = new double[item];
int[] itemStockArr = new int[item];
int[] itemRateArr = new int[item];
// ask to enter price for produect
for (int i = 0; i < item; i++)
{
Clear();
ItemInfo(i, out itemNameArr[i], out itemPriceArr[i], itemStockArr[i], itemRateArr[i]);
Clear();
}
string ans;
do
{
WriteLine("What would you like to do next?");
WriteLine(" Enter 1 to display individual course" + " and 2 to add a new product");
int option = int.Parse(ReadLine());
int result = int.Parse(ReadLine());
switch (option)
{
case 1:
DisplayItems(itemNArr,itemNameArr,itemPriceArr, itemStockArr, itemRateArr);
break;
case 2:
result = ItemInfo(itemN, itemName,itemPrice,itemNStock,itemRating);
break;
default:
WriteLine("No valid entery was entered. " + "i decided to exit the application.... ");
break;
}
WriteLine("\n\nWould you like to do another operation?");
ans = ReadLine();
} while (ans == "Yes" || ans == "yes");
WriteLine("\n\nThank you for choosing our application.... coma back again :) ");
}
public static int AppIntro()
{
WriteLine("Welcome to the PSO App: ");
WriteLine("You will be asked to enter the product name" + " product price, how many you have in stock of the product" + " and the rate of the product");
WriteLine("Then you will have a choise to display individual product" + "info");
WriteLine("\n\nHow many products you want to add!?");
return int.Parse(ReadLine());
}
public static void ItemInfo(int itemN, out string itemName, out double itemPrice, int itemNStock, int itemRating)
{
Write(" Enter the item number {0}:", itemN+1);
itemName = ReadLine();
Write(" Enter the item name: ");
itemName = ReadLine();
Write(" Enter the item price: ");
itemPrice = double.Parse(ReadLine());
Write(" Enter the number of the item in stock: ");
itemNStock = int.Parse(ReadLine());
Write(" Enter the rate of the item: ");
itemRating = int.Parse(ReadLine());
}
public static void DisplayItems(string[]itemN, string[] itemName, double[] itemPrice, int[] itemNStock, int[] itemRating)
{
Write(" Which items would you like to display? Enter it's number: ");
string valueIn = ReadLine();
int n = 0;
for(int i=0; i < itemN.Length; i++)
{
if(valueIn == itemN[i])
{
n = i;
}
Clear();
WriteLine("Your item info: ");
WriteLine("item number is: " + itemN[n]);
WriteLine("item name is: " + itemName[n]);
WriteLine(" item price is: " + itemPrice[n]);
WriteLine(" number of item in the stock is: " + itemNStock[n]);
WriteLine(" item rate is: " + itemRating[n]);
}
}
}
}
I was close to the answer and finally i want to say that here is the answer of my questions.
using System;
using System.Security.Cryptography.X509Certificates;
using static System.Console;
namespace program
{
class UseItem
{
public static void Main(string[] args)
{
int n = 0;
int item = AppIntro();
string[] itemNArr = new string[item];
string[] itemNameArr = new string[item];
double[] itemPriceArr = new double[item];
int[] itemStockArr = new int[item];
int[] itemRateArr = new int[item];
// ask to enter price for produect
//for (int i = 0; i < item; i++)
//{
//Clear();
n = ItemInfo(n, itemNArr, itemNameArr, itemPriceArr, itemStockArr, itemRateArr);
//Clear();
//}
string ans;
do
{
// WriteLine("What would you like to do next?");
WriteLine(" Enter 1 to display individual course" + " and 2 to add a new product");
int option = int.Parse(ReadLine());
//int result = int.Parse(ReadLine());
switch (option)
{
case 1:
DisplayItems(itemNArr,itemNameArr,itemPriceArr, itemStockArr, itemRateArr);
break;
case 2:
n = ItemInfo(n, itemNArr, itemNameArr, itemPriceArr, itemStockArr, itemRateArr);
break;
default:
WriteLine("No valid entery was entered. " + "i decided to exit the application.... ");
break;
}
WriteLine("\n\nWould you like to do another operation?");
ans = ReadLine();
} while (ans == "Yes" || ans == "yes");
WriteLine("\n\nThank you for choosing our application.... come back again :) ");
}
public static int AppIntro()
{
WriteLine("Welcome to the PSO App: ");
WriteLine("You will be asked to enter the product name" + " product price, how many you have in stock of the product" + " and the rate of the product");
WriteLine("Then you will have a choise to display individual product" + "info");
WriteLine("\n\nHow many products you want to add!?");
return int.Parse(Console.ReadLine());
}
public static int ItemInfo(int n, string[] itemN, string[] itemName, double[] itemPrice, int[] itemNStock, int[] itemRating)
{
Write(" Enter the item number:");
itemN[n] = ReadLine();
Write(" Enter the item name: ");
itemName[n] = ReadLine();
Write(" Enter the item price: ");
itemPrice[n] = double.Parse(ReadLine());
Write(" Enter the number of the item in stock: ");
itemNStock[n] = int.Parse(ReadLine());
Write(" Enter the rate of the item: ");
itemRating[n] = int.Parse(ReadLine());
n++;
return n;
}
public static void DisplayItems(string[]itemN, string[] itemName, double[] itemPrice, int[] itemNStock, int[] itemRating)
{
Write(" Which items would you like to display? Enter it's number: ");
string valueIn = ReadLine();
int n = 0;
for(int i=0; i < itemN.Length; i++)
{
if(valueIn == itemN[i])
{
n = i;
}
Clear();
WriteLine("Your item info: ");
WriteLine("item number is: " + itemN[n]);
WriteLine("item name is: " + itemName[n]);
WriteLine(" item price is: " + itemPrice[n]);
WriteLine(" number of item in the stock is: " + itemNStock[n]);
WriteLine(" item rate is: " + itemRating[n]);
}
}
}
}
Just started learning C#, my question is how do i keep record of the user input in order like this: score 1:
score 1: 98
score 2: 76
score 3: 65
score 4: 78
score 5: 56
In my code i can input the number but cant seem to setup the order how can i achieve this goal
my input:
98
76
65
78
56
code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyGrade03
{
public class Program
{
private int total; // sum of grades
private int gradeCounter; //number of grades entered
private int aCount; // Count of A grades
private int bCount; // Count of B grades
private int cCount; // Count of C grades
private int dCount; // Count of D grades
private int fCount; // Count of F grades
private string v;
public string CourseName { get; set; }
public Program(string name)
{
CourseName = name;
}
public void DisplayMessage()
{
Console.WriteLine("Welcome to the grade book for \n{0}!\n",
CourseName);
}
public void InputGrade()
{
int grade;
string input;
Console.WriteLine("{0}\n{1}",
"Enter the integer grades in the range 0-100",
"Type <Ctrl> z and press Enter to terminate input:");
input = Console.ReadLine(); //read user input
while (input != null)
{
grade = Convert.ToInt32(input); //read grade off user input
total += grade;// add grade to total
gradeCounter++; // increment number of grades
IncrementLetterGradeCounter(grade);
input = Console.ReadLine();
}
}
private void IncrementLetterGradeCounter(int grade)
{
switch (grade / 10)
{
case 9: //grade was in the 90s
case 10:
++aCount;
break;
case 8:
++bCount;
break;
case7:
++cCount;
case6:
++dCount;
break;
default:
++fCount;
break;
}
}
public void DisplayGradeReport()
{
Console.WriteLine("\nGrade Report");
if (gradeCounter != 0)
{
double average = (double)total / gradeCounter;
Console.WriteLine("Total of the {0} grades entered is {1}",
gradeCounter, total);
Console.WriteLine("class average is {0:F}", average);
Console.WriteLine("{0}A: {1}\nB: {2}\nC: {3}\nD: {4}\nF: {5} ",
"Number of students who received each grade: \n",
aCount,
bCount,
cCount,
dCount,
fCount);
}
else
Console.WriteLine("No grades were entered");
}
static void Main(string[] args)
{
Program mygradebook = new Program(
"CS101 introduction to C3 programming");
mygradebook.DisplayMessage();
mygradebook.InputGrade();
mygradebook.DisplayGradeReport();
}
}
}
There are a lot of data structures that will allow you to store data in order. I'd personally recommend a List<int> for this.
You can add things to it as simply as:
var list = new List<int>();
list.Add(37);
list.Add(95);
And you can either read it with an iterator (foreach(var score in list){...}) or get individual numbers out (var firstScore = list[0]). The documentation will tell you more about what you can do with a List<T>.
declare one variable to count inputs like private static int counter = 0;
in InputGrade method, put like below
Console.WriteLine("{0}\n{1}",
"Enter the integer grades in the range 0-100",
"Type <Ctrl> z and press Enter to terminate input:");
counter++;
System.Console.Write("score " + counter + ":");
input = Console.ReadLine(); //read user input
and inside while (input != null) put like below
IncrementLetterGradeCounter(grade);
counter++;
System.Console.Write("score " + counter + ":");
input = Console.ReadLine();
so, output will be like
Here is the full code
public class Program
{
private int total; // sum of grades
private int gradeCounter; //number of grades entered
private int aCount; // Count of A grades
private int bCount; // Count of B grades
private int cCount; // Count of C grades
private int dCount; // Count of D grades
private int fCount; // Count of F grades
private string v;
private static int counter = 0;
public string CourseName { get; set; }
public Program(string name)
{
CourseName = name;
}
public void DisplayMessage()
{
Console.WriteLine("Welcome to the grade book for \n{0}!\n",
CourseName);
}
public void InputGrade()
{
int grade;
string input;
Console.WriteLine("{0}\n{1}",
"Enter the integer grades in the range 0-100",
"Type <Ctrl> z and press Enter to terminate input:");
counter++;
System.Console.Write("score " + counter + ":");
input = Console.ReadLine(); //read user input
while (input != null)
{
grade = Convert.ToInt32(input); //read grade off user input
total += grade;// add grade to total
gradeCounter++; // increment number of grades
IncrementLetterGradeCounter(grade);
counter++;
System.Console.Write("score " + counter + ":");
input = Console.ReadLine();
}
}
private void IncrementLetterGradeCounter(int grade)
{
switch (grade / 10)
{
case 9: //grade was in the 90s
case 10:
++aCount;
break;
case 8:
++bCount;
break;
case7:
++cCount;
case6:
++dCount;
break;
default:
++fCount;
break;
}
}
public void DisplayGradeReport()
{
Console.WriteLine("\nGrade Report");
if (gradeCounter != 0)
{
double average = (double)total / gradeCounter;
Console.WriteLine("Total of the {0} grades entered is {1}",
gradeCounter, total);
Console.WriteLine("class average is {0:F}", average);
Console.WriteLine("{0}A: {1}\nB: {2}\nC: {3}\nD: {4}\nF: {5} ",
"Number of students who received each grade: \n",
aCount,
bCount,
cCount,
dCount,
fCount);
}
else
Console.WriteLine("No grades were entered");
}
static void Main(string[] args)
{
Program mygradebook = new Program(
"CS101 introduction to C3 programming");
mygradebook.DisplayMessage();
mygradebook.InputGrade();
mygradebook.DisplayGradeReport();
Console.ReadKey();
}
}
You can look for Collections available in C# (MSDN Collections).
In your case, you don't really care about order, you can use List<int>. Otherwise if you want to keep an order you can use Stack<int> or Queue<int>. And if you want to keep a collection of Student Name + Score you can use a Dictionary<string,int>
I am working on a school project and I have spent 5 hours trying to understand how to go about sorting an Array with an object containing four dimensions. What I set out to do was to sort them by productCode or drinkName. When I read assorted threads people tell OP to use LINQ. I am not supposed to use that and, I get more and more confused as what method to use. I am told by the teacher, to use bubble sort(bad algorithm, I know) and I do that all fine on an Array containing one dimension. I resorted to try Array.Sort but then I get System.InvalidOperationException.
I am going insane and I am stuck even though I read multiple threads on the subject. I might be using ToString in the wrong manner. Any nudge would be appreciated.
class soda
{
string drinkName;
string drinkType;
int drinkPrice;
int productCode;
//Construct for the beverage
public soda(string _drinkName, string _drinkType, int _drinkPrice, int _productCode)
{
drinkName = _drinkName;
drinkType = _drinkType;
drinkPrice = _drinkPrice;
productCode = _productCode;
}
//Property for the drink name e.g. Coca Cola, Ramlösa or Pripps lättöl
public string Drink_name()
{
return drinkName;
//set { drinkName = value; }
}
//Property for the drink type e.g. Soda, fizzy water or beer
public string Drink_type()
{
return drinkType;
//set { drinkType = value; }
}
//Property for the drink price in SEK
public int Drink_price()
{
return drinkPrice;
//set { drinkPrice = value; }
}
//Property for the product code e.g. 1, 2 or ...
public int Product_code()
{
return productCode;
//set { productCode = value; }
}
//Property for the product code e.g. 1, 2 or ...
public int _Product_code
{
get { return productCode; }
set { productCode = value; }
}
public override string ToString()
{
return string.Format(drinkName + " " + drinkType + " " + drinkPrice + " " + productCode);
//return string.Format("The beverage {0} is of the type {1} and costs {2} SEK.", drinkName, drinkType, drinkPrice, productCode);
}
}
class Sodacrate
{
private soda[] bottles; //Crate the array bottles from the class soda.
private int antal_flaskor = 0; //Keeps tracks on the amount of bottles. 25 is the maximum allowed.
//Construct
public Sodacrate()
{
bottles = new soda[25];
}
public void sort_sodas()
{
string drinkName = "";
int drinkPrice = 0;
int productCode = 0;
Array.Sort(bottles, delegate (soda bottle1, soda bottle2) { return bottle1._Product_code.CompareTo(bottle2._Product_code); });
foreach (var beverage in bottles)
{
if (beverage != null)
{
drinkName = beverage.Drink_name(); drinkPrice = beverage.Drink_price(); productCode = beverage.Product_code();
Console.Write(drinkName + " " + drinkPrice + " " + productCode);
}
}
}
}
----------------------edit---------------
Thanks for the help I am getting closer to my solution and have to thursday lunch on me to solve my problems.
Still I have problem with my sort;
//Exception error When I try to have .Product_Name the compiler protests. Invalid token
public void sort_Sodas()
{
int max = bottles.Length;
//Outer loop for complete [bottles]
for (int i = 1; i < max; i++)
{
//Inner loop for row by row
int nrLeft = max - i;
for (int j = 0; j < (max - i); j++)
{
if (bottles[j].Product_code > bottles[j + 1].Product_code)
{
int temp = bottles[j].Product_code;
bottles[j] = bottles[j + 1];
bottles[j + 1].Product_code = temp;
}
}
}
}
Also my Linear search only returns one vallue when I want all those that are true to the product group. I tried a few different things in the Run() for faster experimentation. I will append the current code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Sodacrate
{
//Soda - contains the properties for the bottles that go in to the crate
class Soda : IComparable<Soda>
{
string drinkName;
string drinkType;
int drinkPrice;
int productCode;
//Construct for the beverage
public Soda(string _drinkName, string _drinkType, int _drinkPrice, int _productCode)
{
drinkName = _drinkName;
drinkType = _drinkType;
drinkPrice = _drinkPrice;
productCode = _productCode;
}
//Property for the drink name e.g. Coca Cola, Ramlösa or Pripps lättöl
public string Drink_name
{
get { return drinkName; }
set { drinkName = value; }
}
//Property for the drink type e.g. Soda, fizzy water or beer
public string Drink_type
{
get { return drinkType; }
set { drinkType = value; }
}
//Property for the drink price in SEK
public int Drink_price
{
get { return drinkPrice; }
set { drinkPrice = value; }
}
//Property for the product code e.g. 1, 2 or ...
public int Product_code
{
get { return productCode; }
set { productCode = value; }
}
//Override for ToString to get text instead of info about the object
public override string ToString()
{
return string.Format("{0,0} Type {1,-16} Price {2,-10} Code {3, -5} ", drinkName, drinkType, drinkPrice, productCode);
}
//Compare to solve my issues with sorting
public int CompareTo(Soda other)
{
if (ReferenceEquals(other, null))
return 1;
return drinkName.CompareTo(other.drinkName);
}
}
static class Screen
{
// Screen - Generic methods for handling in- and output ======================================= >
// Methods for screen handling in this object are:
//
// cls() Clear screen
// cup(row, col) Positions the curser to a position on the console
// inKey() Reads one pressed key (Returned value is : ConsoleKeyInfo)
// inStr() Handles String
// inInt() Handles Int
// inFloat() Handles Float(Singel)
// meny() Menu system , first invariable is Rubrik and 2 to 6 meny choises
// addSodaMenu() The options for adding bottles
// Clear Screen ------------------------------------------
static public void cls()
{
Console.Clear();
}
// Set Curser Position ----------------------------------
static public void cup(int column, int rad)
{
Console.SetCursorPosition(column, rad);
}
// Key Input --------------------------------------------
static public ConsoleKeyInfo inKey()
{
ConsoleKeyInfo in_key; in_key = Console.ReadKey(); return in_key;
}
// String Input -----------------------------------------
static public string inStr()
{
string in_string; in_string = Console.ReadLine(); return in_string;
}
// Int Input -------------------------------------------
static public int inInt()
{
int int_in; try { int_in = Int32.Parse(Console.ReadLine()); }
catch (FormatException) { Console.WriteLine("Input Error \b"); int_in = 0; }
catch (OverflowException) { Console.WriteLine("Input Owerflow\b"); int_in = 0; }
return int_in;
}
// Float Input -------------------------------------------
static public float inFloat()
{
float float_in; try { float_in = Convert.ToSingle(Console.ReadLine()); }
catch (FormatException) { Console.WriteLine("Input Error \b"); float_in = 0; }
catch (OverflowException) { Console.WriteLine("Input Owerflow\b"); float_in = 0; }
return float_in;
}
// Menu ------------------------------------------------
static public int meny(string rubrik, string m_val1, string m_val2)
{ // Meny med 2 val ---------------------
int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menSvar = menyInm();
return menSvar;
}
static public int meny(string rubrik, string m_val1, string m_val2, string m_val3)
{ // Meny med 3 val ---------------------
int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menyRad(m_val3); menSvar = menyInm();
return menSvar;
}
static public int meny(string rubrik, string m_val1, string m_val2, string m_val3, string m_val4)
{ // Meny med 4 val ---------------------
int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menyRad(m_val3); menyRad(m_val4); menSvar = menyInm();
return menSvar;
}
static public int meny(string rubrik, string m_val1, string m_val2, string m_val3, string m_val4, string m_val5)
{ // Meny med 5 val ---------------------
int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menyRad(m_val3); menyRad(m_val4); menyRad(m_val5); menSvar = menyInm();
return menSvar;
}
static public int meny(string rubrik, string m_val1, string m_val2, string m_val3, string m_val4, string m_val5, string m_val6)
{ // Meny med 6 val ---------------------
int menSvar; menyRubrik(rubrik); menyRad(m_val1); menyRad(m_val2); menyRad(m_val3); menyRad(m_val4); menyRad(m_val5); ; menyRad(m_val6); menSvar = menyInm();
return menSvar;
}
static void menyRubrik(string rubrik)
{ // Meny rubrik --------
cls(); Console.WriteLine("\n\t {0}\n----------------------------------------------------\n", rubrik);
}
static void menyRad(string menyVal)
{ // Meny rad --------
Console.WriteLine("\t {0}", menyVal);
}
static int menyInm()
{ // Meny inmating ------
int mVal; Console.Write("\n\t Menyval : "); mVal = inInt(); return mVal;
}
// Menu for adding bottles --------------------------------
static public void addSodaMenu()
{
cls();
Console.WriteLine("\tChoose a beverage please.");
Console.WriteLine("\t1. Coca Cola");
Console.WriteLine("\t2. Champis");
Console.WriteLine("\t3. Grappo");
Console.WriteLine("\t4. Pripps Blå lättöl");
Console.WriteLine("\t5. Spendrups lättöl");
Console.WriteLine("\t6. Ramlösa citron");
Console.WriteLine("\t7. Vichy Nouveu");
Console.WriteLine("\t9. Exit to main menu");
Console.WriteLine("\t--------------------\n");
}
// Screen - Slut <========================================
} // screen <----
class Sodacrate
{
// Sodacrate - Methods for handling arrays and lists of Soda-objects ======================================= >
// Methods for Soda handling in this object are:
//
// cls() Clear screen
//
//
private Soda[] bottles; //Create they array where we store the up to 25 bottles
private int antal_flaskor = 0; //Keep track of the number of bottles in the crate
//Inte Klart saknar flera träffar samt exception
public int find_Soda(string drinkname)
{
//Betyg C
//Beskrivs i läroboken på sidan 147 och framåt (kodexempel på sidan 149)
//Man ska kunna söka efter ett namn
//Man kan använda string-metoderna ToLower() eller ToUpper()
for (int i = 0; i < bottles.Length; i++)
{
if (bottles[i].Drink_name == drinkname)
return i;
}
return -1;
}
//Exception error
public void sort_Sodas()
{
int max = bottles.Length;
//Outer loop for complete [bottles]
for (int i = 1; i < max; i++)
{
//Inner loop for row by row
int nrLeft = max - i;
for (int j = 0; j < (max - i); j++)
{
if (bottles[j].Product_code > bottles[j + 1].Product_code)
{
int temp = bottles[j].Product_code;
bottles[j] = bottles[j + 1];
bottles[j + 1].Product_code = temp;
}
}
}
}
/*
//Exception error
public void sort_Sodas_name()
{
int max = bottles.Length;
//Outer loop for complete [bottles]
for (int i = 1; i < max; i++)
{
//Inner loop for row by row
int nrLeft = max - i;
for (int j = 0; j < (max - i); j++)
{
if (bottles[j].Drink_name > bottles[j + 1].Drink_name)
{
int temp = bottles[j].Drink_name;
bottles[j] = bottles[j + 1];
bottles[j + 1].Drink_name = temp;
}
}
}
}
*/
//Search for Product code
public int LinearSearch(int key)
{
for (int i = 0; i < bottles.Length; i++)
{
if (bottles[i].Product_code == key)
return i;
}
return -1;
}
//Contains the menu to choose from the crates methods
public void Run()
{
bottles[0] = new Soda("Coca Cola", "Soda", 5, 1);
bottles[1] = new Soda("Champis", "Soda", 6, 1);
bottles[2] = new Soda("Grappo", "Soda", 4, 1);
bottles[3] = new Soda("Pripps Blå", "beer", 6, 2);
bottles[4] = new Soda("Spendrups", "beer", 6, 2);
bottles[5] = new Soda("Ramlösa", "water", 4, 3);
bottles[6] = new Soda("Loka", "water", 4, 3);
bottles[7] = new Soda("Coca Cola", "Soda", 5, 1);
foreach (var beverage in bottles)
{
if (beverage != null)
Console.WriteLine(beverage);
}
Console.WriteLine("\n\tYou have {0} bottles in your crate:\n\n", bottleCount());
Console.WriteLine("\nTotal value of the crate\n");
int total = 0;
for (int i = 0; i < bottleCount(); i++)
{
total = total + (bottles[i].Drink_price);
}
/* int price = 0; //Causes exception error
foreach(var bottle in bottles)
{
price = price + bottle.Drink_price;
}
*/
Console.WriteLine("\tThe total value of the crate is {0} SEK.", total);
// Console.WriteLine("\tThe total value of the crate is {0} SEK.", price);
Screen.inKey();
Screen.cls();
int test = 0;
test = bottles[3].Product_code;
Console.WriteLine("Product code {0} is in slot {1}", test, 3);
Screen.inKey();
Console.WriteLine("Type 1, 2 or 3");
int prodcode = Screen.inInt();
Console.WriteLine(LinearSearch(prodcode));
Console.WriteLine("Product code {0} is in slot {1}", prodcode, (LinearSearch(prodcode)));
Console.WriteLine(bottles[(LinearSearch(prodcode))]);
Screen.inKey();
// sort_Sodas(); //Causes Exception error I want it to sort on either product code or product name
foreach (var beverage in bottles)
{
if (beverage != null)
Console.WriteLine(beverage);
}
}
//Print the content of the crate to the console
public void print_crate()
{
foreach (var beverage in bottles)
{
if (beverage != null)
Console.WriteLine(beverage);
//else
//Console.WriteLine("Empty slot");
}
Console.WriteLine("\n\tYou have {0} bottles in your crate:", bottleCount());
}
//Construct, sets the Sodacrate to hold 25 bottles
public Sodacrate()
{
bottles = new Soda[25];
}
// Count the ammounts of bottles in crate
public int bottleCount()
{
int cnt = antal_flaskor;
// Loop though array to get not empty element
foreach (var beverages in bottles)
{
if (beverages != null)
{
cnt++;
}
}
return cnt;
}
//Calculates the total value of the bottles in the crate
public int calc_total()
{
int temp = 0;
for (int i = 0; i < bottleCount(); i++)
{
temp = temp + (bottles[i].Drink_price);
}
return temp;
}
//Adds bottles in the crate.
public void add_Soda()
{
/*Metod för att lägga till en läskflaska
Om ni har information om både pris, läsktyp och namn
kan det vara läge att presentera en meny här där man kan
välja på förutbestämda läskflaskor. Då kan man också rätt enkelt
göra ett val för att fylla läskbacken med slumpade flaskor
*/
//I start of with adding 7 bottles to avoid having to add so many bottles testing functions. Remove block before release
bottles[0] = new Soda("Coca Cola", "Soda", 5, 1);
bottles[1] = new Soda("Champis", "Soda", 6, 1);
bottles[2] = new Soda("Grappo", "Soda", 4, 1);
bottles[3] = new Soda("Pripps Blå", "lättöl", 6, 2);
bottles[4] = new Soda("Spendrups", "lättöl", 6, 2);
bottles[5] = new Soda("Ramlösa citron", "mineralvatten", 4, 3);
bottles[6] = new Soda("Vichy Nouveu", "mineralvatten", 4, 3);
//<======================================================================================================= End block
int beverageIn = 0; //Creates the menu choice-variable
while (beverageIn != 9) //Exit this menu by typing 9 - This value should be different if we add more bottle types to add.
{
Screen.addSodaMenu(); //Calls the menu in the Screen-class
Console.WriteLine("You have {0} bottles in the crate.\n\nChoose :", bottleCount());
Screen.cup(8, 13);
int i = bottleCount(); //Keeps track of how many bottles we have in the crate. If the crate is full we get expelled out of this method
if (i == 25)
{ beverageIn = 9; }
else beverageIn = Screen.inInt(); //end
switch (beverageIn) //Loop for adding bottles to the crate exit by pressing 9
{
case 1:
i = bottleCount();
bottles[i] = new Soda("Coca Cola", "Soda", 5, 1);
i++;
break;
case 2:
i = bottleCount();
bottles[i] = new Soda("Champis", "Soda", 6, 1);
i++;
break;
case 3:
i = bottleCount();
bottles[i] = new Soda("Grappo", "Soda", 4, 1);
i++;
break;
case 4:
i = bottleCount();
bottles[i] = new Soda("Pripps Blå lättöl", "lättöl", 6, 2);
i++;
break;
case 5:
i = bottleCount();
bottles[i] = new Soda("Spendrups lättöl", "lättöl", 6, 2);
i++;
break;
case 6:
i = bottleCount();
bottles[i] = new Soda("Ramlösa citron", "mineralvatten", 4, 3);
i++;
break;
case 7:
i = bottleCount();
bottles[i] = new Soda("Vichy Nouveu", "mineralvatten", 4, 3);
i++;
break;
case 9:
i = bottleCount();
if (i == 25)
{
Console.WriteLine("\tThe crate is full\n\tGoing back to main menu. Press a key: ");
}
Console.WriteLine("Going back to main menu. Press a key: ");
break;
default: //Default will never kick in as I have error handling in Screen.inInt()
Console.WriteLine("Error, pick a number between 1 and 7 or 9 to end.");
break;
}
}
}
// Sodacrate - End <========================================
class Program
{
public static void Main(string[] args)
{
//Skapar ett objekt av klassen Sodacrate som heter Sodacrate
var Sodacrate = new Sodacrate();
Sodacrate.Run();
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
}
In order to sort objects of a given kind you need to know how to compare two objects to begin with. You can sort an array of numbers because you know how to comparte 1 with 2 and 2 with -10 and so on.
Nowhere in your code are you defining how two sodas (that should be Soda by the way) compare to each other. One way to do this in c# (and .NET in general) is making your class implement a very specific interface named IComparable<T>:
public interface IComparable<T>
{
int CompareTo(T other);
}
CompareTo is what sorting algorithms like Array.Sort or Linq's OrderBy use (if not told otherwise). You need to do the same. T is a generic type, in your case you are interested in comparing sodas with sodas, so T would be Soda.
The CompareTo convention in .NET is as follows:
If this equals other return 0.
If this is less than other return -1.
If this is greater than other return 1.
null is considered to be smaller than any non null value.
Your implementation must follow this convention in order for built in sorting algorithms to work.
So first off, you need to define how you want your soda's to compare. By name? By price? All seem logical choices. If your problem specifies how sodas should compare then implement the comparison logic accordingly, otherwise choose a reasonable option.
I'll go with ordering by name, so I'd do the following:
public class Soda: IComparable<Soda>
{
....
public int CompareTo(Soda other)
{
if (ReferenceEquals(other, null))
return 1;
return drinkName.CompareTo(other.drinkName);
}
}
Because string implements IComparable<string>, implementing my own comparison logic is pretty straightforward.
Ok, now sodas know how to compare to each other and things like Array.Sort will work perfectly fine. Your own bubble sort algorithm should work well too, now that you know how to compare your softdrinks.
Another option would be to implement a IComparer<T> which is basically an object that knows how to compare two Sodas. Look into it, although in your case I think implementing IComparable<T> is a cleaner solution.
On another page, there are a few things about your code that can and should be improved:
soda should be named Soda. Classes should start with a capital letter (except maybe private nested ones).
Use properties instead of methods for Drink_name, Drink_price, Drink_type etc. and better yet, use autoimplemented properties to reduce boilerplate code.
Remove Drink form property names, the class is named Soda, so Drink is pretty much redundant not adding any useful information; its just making property names longer for no reason.
If you insist on keeping Drink use camel casing and remove _: DrinkName, DrinkType, etc.
I have a basic class that has four attributes (Patient). In Main() I have reserved the memory for the array and before I actually create the instance, I ask the user for the account number to ensure it doesn't already exist within the array. So BinarySearch requires it to be sorted but as soon as I sort it the ability to do the for loop is lost.
//Variables
int intMaxNum = 5; //set max number of patients to 5
int intInputValue;
int intResult;
string strTempName;
int intTempAge;
double dblTempTotal;
Patient[] objectPatient = new Patient[intMaxNum]; //create an array of references
for (int x = 0; x < objectPatient.Length; ++x)
{
//attempt to create a 'shadow' class to search through and keep integrity of main class (objectPatient)
Patient[] tempobjectPatient = new Patient[intMaxNum];
tempobjectPatient = objectPatient;
if (x > 0)
{
Console.Write("\n***Next Patient***");
Array.Sort(tempobjectPatient); //this will sort both objects even though I send the temporary class only - interface impact I'm sure
}
//ask for the Patient Account number
Console.Write("\nEnter Patient Account Number: ");
ReadTheAccountNumber:
intInputValue = Convert.ToInt32(Console.ReadLine());
//create temporary class for comparison
Patient SeekPatient = new Patient();
SeekPatient.PatientNumber=intInputValue; // reset the default info with the input Pateint Account Number
//verify the Patient Account number doesn't already exist
intResult = Array.BinarySearch(tempobjectPatient, SeekPatient);
//intResult = Array.BinarySearch(objectPatient, SeekPatient);
//if (objectPatient.Equals(SeekPatient)) //Can not get the .Equals to work at all...
if (intResult >= 0)
{
Console.Write("\nSorry, Patient Account Number {0} is a duplicate.", intInputValue);
Console.Write("\nPlease re-enter the Patient Account Number: ");
goto ReadTheAccountNumber;
}
else //no match found, get the rest of the data and create the object
{
if (x > 0) { Console.Write("***Patient Account Number unique and accepted***\n"); } //looks silly to display this if entering the first record
Console.Write("Enter the Patient Name: ");
strTempName = Console.ReadLine();
Console.Write("Enter the Patient Age: ");
intTempAge = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the total annual Patient amount due: ");
dblTempTotal = Convert.ToDouble(Console.ReadLine());
objectPatient[x] = new Patient(intInputValue, strTempName, intTempAge, dblTempTotal);
}
}
Here is the class:
class Patient : IComparable
{
//Data fields
private int patientNumber;
private string patientName;
private int patientAge;
private double patientAmountDue;
//Constructors
public Patient(): this(9,"ZZZ",0,0.00)
{
}
public Patient(int _patientNumber, string _patientName, int _patientAge, double _patientAmountDue)
{
PatientNumber = _patientNumber;
PatientName = _patientName;
PatientAge = _patientAge;
PatientAmountDue = _patientAmountDue;
}
//Properties
public int PatientNumber
{
get { return patientNumber; }
set { patientNumber = value; }
}
public string PatientName
{
get { return patientName; }
set { patientName = value; }
}
public int PatientAge
{
get { return patientAge; }
set { patientAge = value; }
}
public double PatientAmountDue
{
get { return patientAmountDue; }
set { patientAmountDue = value; }
}
//Interfaces
int IComparable.CompareTo(Object o)
{
int returnVal; //temporary value container
Patient temp = (Patient)o; //create temp instance of the class
if (this.PatientNumber > temp.PatientNumber)
returnVal = 1;
else
if (this.PatientNumber < temp.PatientNumber)
returnVal = -1;
else
returnVal = 0; //exact match
return returnVal;
}
}
You can put all the patient numbers into HashSet<int> and test via Contains() if a number is allocated one:
class Patient : IComparable {
...
// Simplest, not thread safe
private static HashSet<int> s_AllocatedPatientNumbers = new HashSet<int>();
public static Boolean IsNumberAllocated(int patientNumber) {
return s_AllocatedPatientNumbers.Contains(patientNumber);
}
public int PatientNumber {
get {
return patientNumber;
}
set {
s_AllocatedPatientNumbers.Remove(patientNumber);
patientNumber = value;
s_AllocatedPatientNumbers.Add(patientNumber);
}
}
}
So whenever you need to test if the number has been allocated you have no need to create a temporal patient, sort the array etc. just one simple call:
if (Patient.IsNumberAllocated(intInputValue)) {
...
}
This
Patient[] tempobjectPatient = new Patient[intMaxNum];
creates a new array and assigns it to tempobjectPatient. But this new array is never used, because here
tempobjectPatient = objectPatient;
you immediately assign the old one to tempobjectPatient. So after this, you don't have two array instances. Both tempobjectPatient and objectPatient refer to the same instance.
You probably want:
Patient[] tempobjectPatient = (Patient[])objectPatient.Clone();
Replace the Array with a Dictionary, it is desigend to be used with unique keys:
Dictionary<int,Patient> patients = new Dictionary<int,Patient>();
while (true)
{
Console.Write("\nEnter Patient Account Number: ");
int number = Convert.ToInt32(Console.ReadLine());
if (patients.ContainsKey(number))
{
Console.Write("\nSorry, Patient Account Number {0} is a duplicate.", number);
Console.Write("\nPlease re-enter the Patient Account Number: ");
continue;
}
Console.Write("***Patient Account Number unique and accepted***\n");
Console.Write("Enter the Patient Name: ");
string name = Console.ReadLine();
Console.Write("Enter the Patient Age: ");
int age = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the total annual Patient amount due: ");
double amountDue = Convert.ToDouble(Console.ReadLine());
patients.Add(number, new Patient(number, name, age, amountDue));
}
The loop is now missing an exit condition.
EDIT:
While this does not answer the question of the title i think it is what the OP was looking for.