Store the user input to parallel arrayin C# - c#

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]);
}
}
}
}

Related

C# How can I write console output to a file?

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/

Pass 2D Array Info to a method in c#

I have an assesment where we have to implement methods in an app to store employees info in a 2D array and display it onscreen. So far the code works ok like this but I can't figure out a way to pass the 2D array information to the case 2 of the switch. It always results in an IndexOutOfRangeException when I try to return the array info from the UserInput method or when creating a method for case 2 and trying to pass the array. This is the code i have, thanks in advance for the help:
using System;
namespace EmployeeFileWithMethods
{
class Program
{
static void Main(string[] args)
{
int numberEmployees = 0;
string[,] table = new string[numberEmployees, 4];
string userInput = "1";
while ( userInput != "0" )
{
userInput = Intro();
switch ( userInput )
{
case "1":
UserInput();
break;
case "2":
Console.Clear();
for ( int user = 0; user < table.GetLength(0); user++ )
{
Console.WriteLine(" User " + ( user + 1 ));
for ( int row = 0; row < table.GetLength(1); row++ )
{
Console.Write(table[user, row] + "\n");
}
Console.WriteLine("");
}
break;
case "0":
break;
default:
{
DefaultCase();
break;
}
}
}
Console.WriteLine("Thanks for using the app!");
Console.ReadLine();
}
public static string Intro()
{
Console.WriteLine("[-------------------------------------------------------------------------------]");
Console.WriteLine(" Welcome to the Edinburgh College App \n What would you like to do?\n 1:Add User\n 2:Show User Info\n 0:Exit");
Console.WriteLine("[-------------------------------------------------------------------------------]");
string userInput = Console.ReadLine();
return userInput;
}
public static void DefaultCase()
{
Console.Clear();
Console.WriteLine("[-------------------------------------------------------------------------------]");
Console.WriteLine(" The option that you entered is invalid. Please try again. ");
Console.WriteLine("[-------------------------------------------------------------------------------]");
}
public static void UserInput()
{
Console.WriteLine("How many employees does your company have?");
int numberEmployees = Convert.ToInt32(Console.ReadLine());
string[,] table = new string[numberEmployees, 4];
for ( int row = 0; row < numberEmployees; row++ )
{
Console.WriteLine("Write the Forename of user " + ( row + 1 ));
string forename = Console.ReadLine();
table[row, 0] = forename;
Console.WriteLine("Write the Surname of user " + ( row + 1 ));
string surname = Console.ReadLine();
table[row, 1] = surname;
while ( true )
{
Console.WriteLine("Write the Phone of user " + ( row + 1 ));
string phone = Console.ReadLine();
if ( phone.Length == 11 )
{
table[row, 2] = phone;
break;
}
else
{
Console.WriteLine("Invalid Phone Number. Please Try Again");
continue;
}
}
while ( true )
{
Console.WriteLine("Write the Email of user " + ( row + 1 ));
string email = Console.ReadLine();
int charPos = email.IndexOf('#');
if ( charPos > 0 )
{
table[row, 3] = email;
break;
}
else
{
Console.WriteLine("Invalid Email. Please Try Again");
continue;
}
}
}
}
}
}
I can't reproduce the exception, but UserInput returns nothing and the table initialized in this method is lost at the return. So the table in Main has a size for the first dim of 0. You should pass the table as a parameter by ref and remove the table declaration in the method:
UserInput(table);
public static void UserInput(ref string[,] table)
But you need to resize this array to add new inputs.
A better and more simple and robust and cleaner way is to use a list of a class entity. Here is the code adapted and improved to use a list of an employee entity. I touched the code a minimum but it can be improved and refactored more, especially the while loops, and also you can use int.TryParse for the number of employees to add.
using System.Collections.Generic;
public class Employee
{
public string Forename { get; set; }
public string Surname { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
}
static private void Main()
{
var employees = new List<Employee>();
string userInput = "1";
while ( userInput != "0" )
{
userInput = Intro();
switch ( userInput )
{
case "1":
UserInput(employees);
break;
case "2":
Console.Clear();
for ( int index = 0; index < employees.Count; index++ )
{
Console.WriteLine(" User " + ( index + 1 ));
Console.WriteLine(" Forename: " + employees[index].Forename);
Console.WriteLine(" Surname: " + employees[index].Surname);
Console.WriteLine(" Phone: " + employees[index].Phone);
Console.WriteLine(" eMail: " + employees[index].Email);
Console.WriteLine("");
}
break;
case "0":
break;
default:
{
DefaultCase();
break;
}
}
}
Console.WriteLine("Thanks for using the app!");
Console.ReadLine();
}
public static void UserInput(List<Employee> employees)
{
Console.WriteLine("How many employees does your company have?");
int countEmployees = employees.Count;
int countEmployeesNew = Convert.ToInt32(Console.ReadLine());
for ( int indexEmployeeNew = 0; indexEmployeeNew < countEmployeesNew; indexEmployeeNew++ )
{
int posEmployeeNew = countEmployees + indexEmployeeNew + 1;
Console.WriteLine("Write the Forename of user " + posEmployeeNew);
string forename = Console.ReadLine();
Console.WriteLine("Write the Surname of user " + posEmployeeNew);
string surname = Console.ReadLine();
string phone = "";
while ( true )
{
Console.WriteLine("Write the Phone of user " + posEmployeeNew);
phone = Console.ReadLine();
if ( phone.Length == 11 ) break;
Console.WriteLine("Invalid Phone Number. Please Try Again");
}
string email = "";
while ( true )
{
Console.WriteLine("Write the Email of user " + posEmployeeNew);
email = Console.ReadLine();
int charPos = email.IndexOf('#');
if ( charPos > 0 ) break;
Console.WriteLine("Invalid Email. Please Try Again");
}
employees.Add(new Employee
{
Forename = forename,
Surname = surname,
Phone = phone,
Email = email
});
}
}

C# Print an array of strings in the reverse order

so I have a problem where when I open my program and select 4 which is supposed to make it display all of the strings in the array but in reverse.
using System.Linq;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace Homework3
{
class Program
{
static void Main(string[] args)
{
int optionIntOne;
int optionIntTwo;
int i;
int num = 0;
decimal k;
string[] names = {"Keyhan", "Adolf", "Niklas", "Jenny",
"Elisa", "Rudolf", "Bengt", "Hassan", "Kajsa", "Maggan"};
Console.WriteLine("Please Select an Option Below:\n1 - Find a student by Index \n" +
"2 - Find student Index by name\n3 - Display all student names with their Index \n" +
"4 - Display all the students in reverse order");
string optionStringone = Console.ReadLine();
bool isNumericOne = Int32.TryParse(optionStringone, out optionIntOne);
Console.Clear();
switch (optionIntOne)
{
case 1:
Console.WriteLine("***FIND Student by ID" + "\n" + "Please select a number between 0 - 9:");
string studentNumber = (Console.ReadLine());
bool isNumericTwo = Int32.TryParse(studentNumber, out optionIntTwo);
if (isNumericTwo == true && optionIntTwo < names.Length)
Console.WriteLine(names[optionIntTwo]);
else
Console.WriteLine("Please enter a valid number");
break;
case 2:
Console.WriteLine("*** FIND Student Index by Name \n Please Print one of the above names");
foreach (string name in names)
Console.WriteLine((name));
Console.WriteLine("\n");
string studentName = (Console.ReadLine().ToUpper());
//ToUpper så slipper loopen göra det på repeat
Console.Clear();
bool b = false;
if (decimal.TryParse(studentName, out k) || studentName == string.Empty)
{
Console.WriteLine("Please Enter a Valid Name");
}
else
{
for (i = 0; i < names.Length; i++)
{
if (names[i].ToUpper() == studentName)
{
b = true;
Console.WriteLine(names[i] + " Has the index of " + i);
break;
}
}
if (b == false)
Console.WriteLine("The Student does not Exist in the List");
}
break;
case 3:
while (num < names.Length)
{
Console.WriteLine(num + " - " + names[num]);
num++;
}
break;
case 4:
while (num < names.Length)
{
Console.WriteLine(names[num].Reverse());
num++;
}
break;
default:
Console.WriteLine("Enter a Valid Number");
break;
}
Console.ReadKey();
}
}
}
(option 3 but to print them in reverse order)
Visual Studio isnt giving me any errors but it outputs like this 1 instead of the reverse order of this 2
Anyone know how to fix?/could point out the problem
First of all this line:
Console.WriteLine(names[num].Reverse());
Is reversing the strings inside the list (so names[0].Reverse() would be "nahyeK") because string is also a list (a list of chars). If you want to reverse the whole list you only write names.Reverse();
read more at: Microsoft docs - Reverse()
So the next step would be to print it out.
When you do list.Reverse(); it will return IEnumerable<TSource> which you can use in a loop to get the names.
string[] names = {"Keyhan", "Adolf", "Niklas", "Jenny",
"Elisa", "Rudolf", "Bengt", "Hassan", "Kajsa", "Maggan"};
IEnumerable<string> reversedList = names.Reverse();
foreach(string name in reversedList)
{
Console.WriteLine(name);
}
I usually use list.Reverse().ToList() so i get a "normal" list again because it's in my opinion easier to use/understand.
There is some options, the namespace system.linq.enumerable got some stuff for that:
.ToArray() - converts it to an Array.
.ToList() - converts it to a List
So the complete solution would be to keep the .Reverse outside the loop like this:
foreach(name in names.Reverse().ToList())
{
Console.WriteLine(name);
}
Here is one option:
static void Main(string[] args)
{
int num = 0;
string[] names = { "Alice", "Bob", "Charles", "Delilah" };
while (num < names.Length)
{
Console.WriteLine(names.Reverse().ElementAt(num));
num++;
}
// Prints
//
// Delilah
// Charles
// Bob
// Alice
Console.ReadKey();
}
As per the comments it is not optimal to call Reverse() in each loop. Instead, perform the Reverse() outside of the loop.
A better alternative might be:
static void Main(string[] args)
{
string[] names = { "Alice", "Bob", "Charles", "Delilah" };
for (int num = names.Length - 1; num >= 0; num--)
{
Console.WriteLine(names[num]);
}
Console.ReadKey();
}

how can i number each user input? C#

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>

checking integers in String

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;
}
}

Categories