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>
Related
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/
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]);
}
}
}
}
Having problem with my work i want to write a program that does the sum and average the student grade in the average function i used a do while loop since i want anyone to enter grade until the user enter -1 the loop end.
The problem is i do not want to run the _cal = Int32.Parse(Console.ReadLine()); in the fucntion instead run it in the main by passing a value to Average() parameter then using the value in main as a console.readlIne because i will use the user input to divide by the sum in order to get average am new to programming.
public static void Main()
{
Console.WriteLine("Please Enter the scores of your student: ");
Console.WriteLine("----------------------------------------");
_studentTotalGrade = Average();
Console.WriteLine("sum " + Sum);
Console.ReadLine();
}
public static double Average()
{
double _cal,_sumTotal = 0;
int i = 0;
do
{
_cal = Int32.Parse(Console.ReadLine());
if (_cal == -1)
{
break;
}
if (_cal > 20)
{
Console.WriteLine("Adjust score\");
continue;
}
_sumTotal +=_cal;
i--;
} while (_cal > i);
return _sumTotal;
}
}
I'm checking a string whether it has integers or anything else in function Parse().
Here is my Code
static public int input()
{
Console.WriteLine("Enter The Number Of Student You Want to get Record");
int x;
string inputString = Console.ReadLine();
if (int.TryParse(inputString, out x))
{
Console.WriteLine(inputString + " Is Integer");
return x= Convert.ToInt32(inputString);
}
else
{
input();
}
return x;
}
And full code is:
static void Main(string[] args)
{
int num = 0;
string[] names = new string[] { };
long[] fee = new long[] { };
string[] className = new string[] { };
do
{
Console.WriteLine("Enter Option You Want: \nA:Enter Student Record\nB:Display Student Record\nQ:Exit");
string option =null;
option =Console.ReadLine();
switch (option)
{
case "A":
case "a":
{
num = input();
names = new string[num];
fee = new long[num];
className = new string[num];
for (int i = 0; i < num; i++)
{
Console.WriteLine("Enter Name Of Student:{0}",i);
Console.Write("Enter Student Name: "); names[i] = Console.ReadLine();
Console.Write("Enter Student Fee: "); fee[i] = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter Student Class Name: "); className[i] = Console.ReadLine();
}
break;
}
case "B":
case "b":
{
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine("Record of Student: {0}",i);
Console.WriteLine("Name: "+names[i]+ "\nFee: " + fee[i]+ "\nClass Name: " + className[i]);
//Console.WriteLine("Name: {0}\n Class Name: {1}\n Fee: {3}\n",names[i],className[i],fee[i]);
}
break;
}
case "Q":
case "q":
{
Environment.Exit(1);
break;
}
default:
{
Console.WriteLine("Invalid Option");
break;
}
}
} while (true);
}
But The problem is when I enters char instead of int and it works fine and calls itself again but if 2nd time or after 2nd time I input int then does not take input of students and instead it repeats the LOOP again.
So what's the problem, is problem in Input Function????
You could use a regular expression to find the INTs. Also you should call
return input();
instead of
input();
new method:
static public int input(){
Console.WriteLine("Enter The Number Of Student You Want to get Record");
string input = Console.ReadLine();
if (Regex.IsMatch(input, #"\d+"))
{
return int.Parse(Regex.Match(input, #"\d+").Value);
}
else
{
return input();
}
}
I'm assuming you're a student. I started out with C# doing the same stuff. Which I wouldn't do anymore but since you are doing it. I'd recommend using goto, making this method recursive is a no no.
static public int input()
{
Prompt:
Console.WriteLine("Enter The Number Of Student You Want to get Record");
int x;
string inputString = Console.ReadLine();
if (int.TryParse(inputString, out x))
{
Console.WriteLine(inputString + " Is Integer");
return x;
}
else
{
goto Prompt;
}
}
here i ask the user for homework scores which are then averaged after discarding the smallest and largest score. i have stored the user input in an array. in my DisplayResults method im not sure how to display the lowest and highest scores that were discarded. any help is appreciated! Here is what i have so far:
class Scores
{
static void Main(string[] args)
{
double sum = 0;
double average = 0;
int arraySize;
double[] inputValues;
arraySize = HowManyScores();
inputValues = new double[arraySize];
GetScores(inputValues);
sum = CalculateSum(inputValues);
average = CaculateAverage(sum, arraySize);
DisplayResults(inputValues, average);
Console.Read();
}
public static int HowManyScores()
{
string input;
int size;
Console.WriteLine("How many homework scores would you like to enter?");
input = Console.ReadLine();
while (int.TryParse(input, out size) == false)
{
Console.WriteLine("Invalid data. Please enter a numeric value.");
input = Console.ReadLine();
}
return size;
}
public static void GetScores(double[] inputValues)
{
double scoreInput;
Console.Clear();
for (int i = 0; i < inputValues.Length; i++)
{
scoreInput = PromptForScore(i + 1);
inputValues[i] = scoreInput;
}
}
public static double PromptForScore(int j)
{
string input;
double scoreInput;
Console.WriteLine("Enter homework score #{0}:", j);
input = Console.ReadLine();
while (double.TryParse(input, out scoreInput) == false)
{
Console.WriteLine("Invalid Data. Your homework score must be a numerical value.");
input = Console.ReadLine();
}
while (scoreInput < 0)
{
Console.WriteLine("Invalid Data. Your homework score must be between 0 and 10.");
input = Console.ReadLine();
}
while (scoreInput > 10)
{
Console.WriteLine("Invalid Data. Your homework score must be between 0 and 10.");
input = Console.ReadLine();
}
return scoreInput;
}
public static double CalculateSum(double[] inputValues)
{
double sum = 0;
for (int i = 1; i < inputValues.Length - 1; i++)
{
sum += inputValues[i];
}
return sum;
}
public static double CaculateAverage(double sum, int size)
{
double average;
average = sum / ((double)size - 2);
return average;
}
public static void DisplayResults(double[] inputValues, double average)
{
Console.Clear();
Console.WriteLine("Average homework score: {0}", average);
//Console.WriteLine("Lowest score that was discarded: {0}",
//Console.WriteLine("Highest score that was discarded: {0}",
}
}
}
You basically only have to do one thing: Sorting the array after you received your input data. Then, printing the first and last value gives you the minimal and maximal score. Use
Array.Sort(intArray);
in main after calling GetScores and
Console.WriteLine("Lowest score: {0} Highest score: {1}",
inputValues[0], inputValues[inputValues.Length - 1]);
to print the results. Cheers
EDIT: The proposal by Jens from the comments using the Min/Max is probably more what you're looking for if you're not interested in complete ordering of your values.