Pass 2D Array Info to a method in c# - 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
});
}
}

Related

Problem with My Class Variables Array is not working as intended - C#

To give some context. So for this project I have an array of my class variables, the cd1. That is the variable for the AudioCD and it is an array because if the user wants to enter more CD in to the array.
The problem I am getting is that when I enter more then one cd into the class array, at around the part where I add the string or artist is where I get the issue. When I go to print the class variables specific index which should be seperate, mostly everything except the artist array for the shows the last entered lines for some weird reason. I am trying to figure out why it is doing this.
PS. Sorry is my explanation is not the best.
As you see in the image. The out put should be when I input 1 for choice and 1 for the CD, the array should use the array for index 0, but it is using the array from the last inputted CD. The output should be:
man1
man2
man3
but it is:
man4
man5
man6
class AudioCD
{
// Private Variables for CDclass
public string cdTitle { get; private set; }
private string[] artists = new string[4];
public int releaseYear { get; private set; }
public string genre { get; private set; }
public float condition { get; private set; }
// Constructor for the CDclass - initializes all variables used in the CDclass
public AudioCD()
{
cdTitle = "";
artists = new string[] {"","","",""};
releaseYear = 1980;
genre = "";
condition = 0.0f;
}
// Overload Constructor for the CDclass - initializes all the variables to user input variables
public AudioCD(string cdt, string[] art, int reY, string gen, float con)
{
cdTitle = cdt;
if (artists.Length < art.Length)
{
Console.WriteLine("Your Array size is bigger then 4 for the Artist so the first 4 names will be used!");
}
artists = art;
if (reY < 1980)
{
releaseYear = 1980;
}
else
{
releaseYear = reY;
}
genre = gen;
if (con < 0.0f || con > 5.0f)
{
condition = 0.0f;
}
else
{
condition = con;
}
}
public void printAudioCD()
{
Console.Write(cdTitle + ", " + releaseYear + "\n" );
for (int i = 0; i < artists.Length; i++)
{
if (artists[i] != "" )
{
Console.WriteLine("Artist (#" + (i + 1) + "): " + artists[i]);
}
}
Console.WriteLine("Genre: " + genre);
Console.WriteLine("Condition: " + condition);
}
}
and Program class:
class Program
{
static void Main(string[] args)
{
// variables
string uI, cdtitle, genre;
int size = 0, releaseYear, choice, arrInd;
string[] artistArray = new string[4] {"", "", "", "" };
float condition;
//
AudioCD remote = new AudioCD();
Console.Write("How many CDs do you have lying around your car? ");
uI = Console.ReadLine();
size = Convert.ToInt32(uI);
AudioCD[] cd1 = new AudioCD[size];
for (int i = 0; i < size; i++)
{
Console.WriteLine("CD #" + (i + 1));
Console.Write("*Enter Title: ");
uI = Console.ReadLine();
cdtitle = uI;
Console.WriteLine("*Enter Artists (type -1 when finished):");
int j = 0;
do
{
uI = Console.ReadLine();
if (uI != "-1")
artistArray[j] = uI;
j++;
// Resize the array by One Element
if (j >= 4 && uI != "-1")
{
Array.Resize(ref artistArray, artistArray.Length + 1);
artistArray[j] = "";
}
} while (uI != "-1" );
Console.Write("*Enter Genre: ");
uI = Console.ReadLine();
genre = uI;
Console.Write("*Enter Release Year: ");
uI = Console.ReadLine();
releaseYear = Convert.ToInt32(uI);
Console.Write("*Enter Condition: ");
uI = Console.ReadLine();
condition = float.Parse(uI);
Console.Write("\n");
// switch to select which class of cd to put information in
cd1[i] = new AudioCD(cdtitle, artistArray, releaseYear, genre, condition);
}
bool isPlaying = true;
while(isPlaying)
{
Console.Write("\n");
Console.WriteLine("[Main Menu]");
Console.WriteLine("1) Album Info");
Console.WriteLine("2) Find a CD");
Console.WriteLine("3) Find an artist");
Console.WriteLine("4) Log off");
Console.Write("Choice: ");
uI = Console.ReadLine();
choice = Convert.ToInt32(uI);
switch(choice)
{
case 1:
{
Console.Write("\nWhich CD do you want? ");
uI = Console.ReadLine();
arrInd = Convert.ToInt32(uI);
if (arrInd >= 1 || arrInd <= size)
{
Console.Write(arrInd + ". ");
cd1[(arrInd - 1)].printAudioCD();
}
break;
}
case 2:
{
break;
}
case 3:
{
break;
}
case 4:
{
isPlaying = false;
break;
}
default:
{
break;
}
}
}
}
}
OUTPUT
As you see in the image. The out put should be when I input 1 for choice and 1 for the CD, the array should use the array for index 0, but it is using the array from the last inputted CD. The output should be man1,man2, and man3, but it is man4, man5, and man6.
You are using the same array in your Main() for each iteration and this is the reason why you got the artists from the last inputted CD. I mean this code snippet:
string[] artistArray = new string[4] {"", "", "", "" };
Here we can use List<T> to avoid writing code of resizing of an array and we can use Clear() method to avoid storing artists from the previous CD.
The whole code would look like this. I've refactored your code a little bit by using List:
The class AudioCD:
public class AudioCD
{
// Private Variables for CDclass
public string cdTitle { get; private set; }
private List<string> artists = new List<string>();
public int releaseYear { get; private set; }
public string genre { get; private set; }
public float condition { get; private set; }
// Constructor for the CDclass - initializes all variables used in the CDclass
public AudioCD()
{
cdTitle = "";
releaseYear = 1980;
genre = "";
condition = 0.0f;
}
// Overload Constructor for the CDclass - initializes all the variables to user input variables
public AudioCD(string cdt, List<string> art, int reY, string gen, float con)
{
cdTitle = cdt;
artists.AddRange(art);
if (reY < 1980)
{
releaseYear = 1980;
}
else
{
releaseYear = reY;
}
genre = gen;
if (con < 0.0f || con > 5.0f)
{
condition = 0.0f;
}
else
{
condition = con;
}
}
public void printAudioCD()
{
Console.Write(cdTitle + ", " + releaseYear + "\n");
for (int i = 0; i < artists.Count; i++)
{
if (artists[i] != "")
{
Console.WriteLine("Artist (#" + (i + 1) + "): " + artists[i]);
}
}
Console.WriteLine("Genre: " + genre);
Console.WriteLine("Condition: " + condition);
}
}
and Main method would look like this:
// variables
string uI, cdtitle, genre;
int size = 0, releaseYear, choice, arrInd;
List<string> artistArray = new List<string>();
float condition;
Console.Write("How many CDs do you have lying around your car? ");
uI = Console.ReadLine();
size = Convert.ToInt32(uI);
AudioCD[] cd1 = new AudioCD[size];
for (int i = 0; i < size; i++)
{
Console.WriteLine("CD #" + (i + 1));
Console.Write("*Enter Title: ");
uI = Console.ReadLine();
cdtitle = uI;
Console.WriteLine("*Enter Artists (type -1 when finished):");
int j = 0;
do
{
uI = Console.ReadLine();
if (uI != "-1")
artistArray[j] = uI;
j++;
} while (uI != "-1");
Console.Write("*Enter Genre: ");
uI = Console.ReadLine();
genre = uI;
Console.Write("*Enter Release Year: ");
uI = Console.ReadLine();
releaseYear = Convert.ToInt32(uI);
Console.Write("*Enter Condition: ");
uI = Console.ReadLine();
condition = float.Parse(uI);
Console.Write("\n");
// switch to select which class of cd to put information in
cd1[i] = new AudioCD(cdtitle, artistArray, releaseYear, genre, condition);
artistArray.Clear();
}
bool isPlaying = true;
while (isPlaying)
{
Console.Write("\n");
Console.WriteLine("[Main Menu]");
Console.WriteLine("1) Album Info");
Console.WriteLine("2) Find a CD");
Console.WriteLine("3) Find an artist");
Console.WriteLine("4) Log off");
Console.Write("Choice: ");
uI = Console.ReadLine();
choice = Convert.ToInt32(uI);
switch (choice)
{
case 1:
{
Console.Write("\nWhich CD do you want? ");
uI = Console.ReadLine();
arrInd = Convert.ToInt32(uI);
if (arrInd >= 1 || arrInd <= size)
{
Console.Write(arrInd + ". ");
cd1[(arrInd - 1)].printAudioCD();
}
break;
}
case 2:
{
break;
}
case 3:
{
break;
}
case 4:
{
isPlaying = false;
break;
}
default:
{
break;
}
}
}

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/

Store the user input to parallel arrayin 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]);
}
}
}
}

C# Loop back to a previous part of code

//Gender Creation:
while (correct == 0)
{
do
{
Console.Clear();
Console.WriteLine("Please choose a gender from the options below: ");
Console.WriteLine("Male|Female|Random");
Console.Write("Input: ");
Gender = Console.ReadLine().ToUpper();
if (Gender == "MALE")
{
Console.WriteLine("Is this the gender you wish your character to be? Enter Yes/No: ");
Console.Write("Input: ");
Input = Console.ReadLine().ToUpper();
if (Input == "YES")
{
correct = 1;
}
else if (Input == "NO")
{
correct = 0;
}
}
else if (Gender == "FEMALE")
{
Console.WriteLine("Is this the gender you wish your character to be? Enter Yes/No: ");
Console.Write("Input: ");
Input = Console.ReadLine().ToUpper();
if (Input == "YES")
{
correct = 1;
}
else if (Input == "NO")
{
correct = 0;
}
}
else if (Gender == "RANDOM")
{
correct = 2;
}
else
{
Console.WriteLine("ERROR, Please try again.");
Gender = Console.ReadLine().ToUpper();
}
} while (correct == 0);
//Random Gender Creation:
if (correct == 2)
{
do
{
if (randgender == 1)
{
Console.WriteLine("The gender: MALE was randomly chosen");
Console.WriteLine("Is this the gender you wish your character to be? Enter Yes/No: ");
Console.Write("Input: ");
Input = Console.ReadLine().ToUpper();
if (Input == "YES")
{
correct = 1;
Gender = "MALE";
}
else if (Input == "NO")
{
correct = 2;
}
}
else if (randgender == 2)
{
Console.WriteLine("The gender: FEMALE was randomly chosen");
Console.WriteLine("Is this the race you wish your character to be? Enter Yes/No: ");
Console.Write("Input: ");
Input = Console.ReadLine().ToUpper();
if (Input == "YES")
{
correct = 1;
Gender = "FEMALE";
}
else if (Input == "NO")
{
correct = 2;
}
}
} while (correct == 2);
correct = 0;
}
break;
}
When correct = 2 then the gender is being randomly generated, if the user inputs no when being asked if they are happy with the gender the code will just loop the random gender generator over and over constantly saying that the random gender is the same every time as the random number is never changing however when correct = 0 the code will just proceed when no is inputted and when the gender is printed it is just printed as RANDOM as that is the option the user initially chose.
How can I make it go back to the first do while loop to ask the user what gender they want their character to be?
As theMayer suggested, you'll need to break down your app into smaller pieces. There are also a few concepts that you may need to tackle before you can write C#, as such.
This example might help you get a little further along, as it illustrates several ways of achieving better control flow:
static void Main(string[] args)
{
Console.Clear();
var choosenGender = "";
var wasChoiceConfirmed = false;
while (wasChoiceConfirmed == false)
{
choosenGender = PromptForGender();
switch (choosenGender)
{
case "RANDOM":
var randomGender = GenerateRandomGender();
wasChoiceConfirmed = PromptForGenderConfirmation(randomGender, true);
break;
case "MALE":
case "FEMALE":
wasChoiceConfirmed = PromptForGenderConfirmation(choosenGender);
break;
default:
Console.WriteLine("Error, please try again. \n");
break;
}
}
}
static string PromptForGender()
{
Console.Write(
"\nPlease choose a gender from the options below: \n" +
"Male|Female|Random \n" +
"Input:");
return Console.ReadLine().Trim().ToUpper();
}
static bool PromptForGenderConfirmation(string gender, bool wasRandom = false)
{
var randomVerbiage = wasRandom ? "randomly " : "";
Console.Write(
$"\nThe gender: {gender} was {randomVerbiage}chosen \n" +
"Is this the gender you wish your character to be? Enter Yes/No: \n" +
"Input: ");
var confirmed = Console.ReadLine().Trim().ToUpper();
return confirmed == "YES";
}
static string GenerateRandomGender()
{
var randomNumber = new Random();
return randomNumber.Next(0, 1) == 0 ? "FEMALE" : "MALE";
}
I refactored your code so it helps me understand it better. This gives you the result you want and you don't need all those nested loops.
public class Program
{
public static void AskFirstQuestion()
{
Console.Clear();
Console.WriteLine("Please choose a gender from the options below: ");
Console.WriteLine("Male|Female|Random");
Console.Write("Input: ");
var gender = Console.ReadLine()?.ToUpper();
if (gender == "MALE" || gender == "FEMALE")
{
HandleGenderSelection(gender);
}
else if (gender == "RANDOM")
{
HandleRandom();
}
}
private static void HandleRandom()
{
var randomGender = GenerateRandomGender();
Console.WriteLine($"The gender: {randomGender} was randomly chosen");
Console.WriteLine("Is this the race you wish your character to be? Enter Yes/No: ");
Console.Write("Input: ");
var input = Console.ReadLine()?.ToUpper();
switch (input)
{
case "YES":
Console.WriteLine("OK");
break;
case "NO":
AskFirstQuestion();
break;
}
}
private static string GenerateRandomGender()
{
//Have you logic to randomly create gender
return "MALE";
}
private static void HandleGenderSelection(string gender)
{
Console.WriteLine("Is this the gender you wish your character to be? Enter Yes/No: ");
Console.Write("Input: ");
var input = Console.ReadLine()?.ToUpper();
if (input == "YES")
{
Console.WriteLine("OK!");
}
else if (input == "NO")
{
AskFirstQuestion();
}
}
static void Main(string[] args)
{
AskFirstQuestion();
}
}

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