Not enter in a switch case in C# - c#

I can't enter in the case 2 of the switch statement and I don't know why. If I remove the do while loop the code runs perfectly. It's about something with the memory of the structure array? Here is the code:
class Notebook {
struct Student
{
public String id;
public String name;
public void showInfo(Student x) {
Console.WriteLine("\t ID: " + x.id);
Console.WriteLine("\t Name: " + x.name);
}
}
static void Main(string[] args){
bool display = true;
int studentNum = int.Parse(Console.ReadLine());
Student[] students = new Student[studentNum];
do {
Console.Clear();
Console.WriteLine("1.- Insert register");
Console.WriteLine("2.- Show register");
Console.WriteLine("3.- Exit");
String opc = Console.ReadLine();
switch (opc) {
case "1":
Console.Clear();
for(int i = 0; i < students.Length; ++i){
Console.WriteLine("Name of the student " + (i+1));
students[i].name = Console.ReadLine();
Console.WriteLine("ID of the student " + (i+1));
students[i].id = Console.ReadLine();
}
break;
case "2":
Console.Clear();
for(int i = 0; i < students.Length; ++i){
students[i].showInfo(students[i]);
}
break;
case "3":
Console.Clear();
Console.WriteLine("bye");
display = false;
break;
}
}while(display);
}
}
I think that is "something" in the memory of opc string that avoids the case 2.

Your problem is the Console.Clear statement that you run at start of do while loop. Comment that line and you will see that your code is going to case "2".
Its going to case "2" even in your original code, but console is every time being cleared at start of do while loop and so you don't see the statements written by case "2" logic.
There is no memory problem as you suspected.
The do while loop should have Console.Clear commented as in code below.
do {
//Console.Clear();
Console.WriteLine("1.- Insert register");
Console.WriteLine("2.- Show register");
Console.WriteLine("3.- Exit");

add a Console.ReadLine(); before break case "2".
case "2":
Console.Clear();
for (int i = 0; i < students.Length; ++i)
{
students[i].showInfo(students[i]);
}
Console.ReadLine();
break;
You write students informations and Call Console.Clear() after that

Related

Return to a specific block of code in my application

I am fairly new to C# and currently building a simple ATM app. I am attempting to write code to return the user to the main menu according to his/her entry of the letter M. The break, continue, goto or return keywords do not seem to work in my scenario; perhaps I used them incorrectly. The statement directly below is where I would like to jump to.
Console.WriteLine("Select an option? \n VIEW BALANCE (B1) checking, (B2) saving \n DEPOSIT (C1) checking, (C2) saving \n WITHDRAW (W1) checking, (W2) saving");
I would like to jump from the line JUMP (below) within the else if statement nested within the switch statement into the section of code above. How can I achieve this? any help is appreciated...thanks!
switch (response)
{
case "C1":
Console.WriteLine("How much would you like to deposit to your checking account?");
string depositEntry = Console.ReadLine();
double checkingBalance = Convert.ToInt32(depositEntry) + currentCheckingBalance;
currentCheckingBalance += checkingBalance;
Console.WriteLine("Your current checking balance is " + checkingBalance + "\n (X) Exit, (M) Main Menu" );
string selection = Console.ReadLine().ToUpper();
if (selection == "X")
{
return;
}
else if (selection == "M")
{
***JUMP***
}
else
{
Console.WriteLine("Your entry was invalid");
}
break;
case "C2":
break;
case "W1":
Using a jump statement usually indicates the flow of logic is jumbled. I try to avoid any kind of jumps if necessary. The code below prints out a main menu and if the user types “x” the program will quit. If the user selects one of the other options, a message is simply printed out indicating what the user selected. After the user presses any key, the console clears and the main menu is re-displayed.
In the main menu, if the user does not type one of the selections, then the selection is ignored, the console is cleared, and the menu is reprinted. No error is displayed indicating invalid selections.
This does not require the user to type “m” to go back to the main menu. After a selection is made for Deposit/withdraw/… after the method is finished the code will automatically return to the main menu.
I am guessing this may be what you are looking for. Hope this helps.
static void Main(string[] args) {
string userInput = "";
while ((userInput = GetMainSelection()) != "x") {
switch (userInput) {
case "c1":
Console.WriteLine("C1 Deposit Checking method");
break;
case "c2":
Console.WriteLine("C2 Deposit Savings method");
break;
case "b1":
Console.WriteLine("B1 View Balance Checking method");
break;
case "b2":
Console.WriteLine("B2 View Balance Savings method");
break;
case "w1":
Console.WriteLine("W1 Withdraw Checking method");
break;
case "w2":
Console.WriteLine("W2 withdraw Savings method");
break;
}
Console.WriteLine("Press Any Key to continue"); // <-- show what method was just used
Console.ReadKey();
Console.Clear();
}
Console.Write("Press any key to exit the program");
Console.ReadKey();
}
private static string GetMainSelection() {
string userInput = "";
while (true) {
Console.WriteLine("Select an option? \n VIEW BALANCE (B1) checking, (B2) saving \n DEPOSIT (C1) checking, (C2) saving \n WITHDRAW (W1) checking, (W2) saving. (X) to EXit");
userInput = Console.ReadLine().ToLower();
if (userInput == "b1" || userInput == "b2" || userInput == "c1" || userInput == "c2" || userInput == "w1" || userInput == "w2" || userInput == "x") {
return userInput;
}
else {
Console.Clear();
}
}
}
Put the JUMP code in a function and return.
public void MainMenu() {
// Show the main menu
}
public void Response(string response) {
switch (response)
{
case "C1":
Console.WriteLine("How much would you like to deposit to your checking account?");
string depositEntry = Console.ReadLine();
double checkingBalance = Convert.ToInt32(depositEntry) + currentCheckingBalance;
currentCheckingBalance += checkingBalance;
Console.WriteLine("Your current checking balance is " + checkingBalance + "\n (X) Exit, (M) Main Menu" );
string selection = Console.ReadLine().ToUpper();
if (selection == "X")
{
return;
}
else if (selection == "M")
{
***JUMP***
MainMenu();
return;
}
else
{
Console.WriteLine("Your entry was invalid");
}
break;
case "C2":
break;
case "W1":
}
}
Similar to the already given answer, I suggest breaking this out. Here's an example:
The Main method:
static void Main(string[] args) {
string input = null;
do {
input = Console.ReadLine();
ParseInput(input);
} while (input != "X");
}
ParseInput:
static void ParseInput(string input) {
switch (input) {
case "X": //from Main(), this will close the app
return;
case "M":
MainMenu();
break;
case "C1":
ShowAccount("C1"); //move your deposit/withdraw logic into a method and call with the selected account
return;
//other accounts
default:
break; //error message?
}
}
and MainMenu:
static void MainMenu() {
Console.WriteLine("Select an option? \n VIEW BALANCE (B1) checking, (B2) saving \n DEPOSIT (C1) checking, (C2) saving \n WITHDRAW (W1) checking, (W2) saving");
}
This should let you read the input in a loop and the ParseInput function can handle your individual cases. You may also want to call MainMenu() at the start, so it shows from the beginning.
It works like this:
Get input from the user
Pass the input to ParseInput() which decides where to go next.
Any functions hit in ParseInput() will execute, writing to the console or asking for further input
Once that function returns, while (input != "X") evaluates. If input != "X", goto 1, else exit.
I suggest you use goto C# reference.
static void Main()
{
int x = 200, y = 4;
int count = 0;
string[,] array = new string[x, y];
// Initialize the array:
for (int i = 0; i < x; i++)
for (int j = 0; j < y; j++)
array[i, j] = (++count).ToString();
// Read input:
Console.Write("Enter the number to search for: ");
// Input a string:
string myNumber = Console.ReadLine();
// Search:
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
if (array[i, j].Equals(myNumber))
{
goto Found;
}
}
}
Console.WriteLine("The number {0} was not found.", myNumber);
goto Finish;
Found:
Console.WriteLine("The number {0} is found.", myNumber);
Finish:
Console.WriteLine("End of search.");
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
Output for the Input 44 would be:
Enter the number to search for: 44
The number 44 is found.
End of search.
See here for the MSDN reference.

c# Having users choose from elements in array

I have a project in which users enter a job description, hours needed, and hourly pay for 5 jobs. Once entered they must choose 2 of the jobs they entered to combine into one job. I'm unsure how to retrieve the job number that they enter from the array (jobArray) (job 1 and job2 for example).
So if they enter in job 1 as mowing, and job 2 as trimming they should have the option to combine both to make mowing and trimming.
Here is my code, any help would be appreciated.
namespace DemoJobs
{
class Class2
{
public static Job[] jobArray = new Job[5];
static void Main(string[] args)
{
string option;
do
{
Console.WriteLine("Menu");
Console.WriteLine("\t1. Enter Jobs");
Console.WriteLine("\t2. Combine 2 Jobs");
Console.WriteLine("\t3. Display All Jobs");
Console.WriteLine("\t4. Exit");
option = Console.ReadLine();
switch (option)
{
case "1":
Console.Clear();
EnterJobs();
break;
case "2":
Console.Clear();
//CombineJobs();
break;
case "3": //display jobs
DisplayAllJobs();
break;
case "4":
break;
default:
Console.WriteLine("Option invalid.");
Console.ReadLine();
break;
}
} while (option != "4");
Console.WriteLine("Press enter to exit the window.");
Console.ReadLine();
}
private static void EnterJobs()
{
for (int i = 0; i < jobArray.Length; i++)
{
// int totFee;
Job job = new Job();
Console.WriteLine("Job " + i);
Console.WriteLine("Enter a job description.");
job.Description = Console.ReadLine();
Console.WriteLine("Enter the amount of hours required to complete the job.");
job.hoursToComplete = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the hourly rate for the job.");
job.hourlyRate = Convert.ToDouble(Console.ReadLine());
jobArray[i] = job;
//calcing total fee
job.totalFee = job.hourlyRate * job.hoursToComplete;
}
Console.WriteLine(" ");
} //end of enterjobs
//combining jobs
private static void CombineJobs(Job first, Job second)
{
Console.WriteLine("Which 2 jobs would you like to combine?");
first.Description = Console.ReadLine();
}
private static void DisplayAllJobs()
{
// jobArray.ToList().Sort();
//sorting jobs from totalFee
Array.Sort(jobArray);
//printing array
Console.WriteLine(jobArray[0].ToString());
Console.WriteLine(jobArray[1].ToString());
Console.WriteLine(jobArray[2].ToString());
Console.WriteLine(jobArray[3].ToString());
Console.WriteLine(jobArray[4].ToString());
}
}
}
You can search the array like this.
Job jobToFind = jobArray.FirstOrDefault(s => s.Description.Equals(first.Description));
Job job2ToFind = jobArray.FirstOrDefault(s => s.Description.Equals(second.Description));
and then combine jobs as you see fit.
newJob.Description = jobToFind.Description + job2ToFind.Description;
// newJob.Pay = more combining here etc.

How to transfer the control of goto statement in C#

I'm beginner in programming and I'm trying this simple program of getting user name and sorting it and so on.
class Program
{
static void Main(string[] args)
{
int number;
dynamic y;
string[] answer = new string[10];
cases:
Console.WriteLine("Enter the options given below 1.Add students\n 2.View all details\n 3.Sorting\n 4.Exit\n");
int input = Convert.ToInt16(Console.ReadLine());
switch (input)
{
case 1:
Console.WriteLine("Enter the Number of Students to be added to the List");
number = Convert.ToInt16(Console.ReadLine());
for (int i = 0; i < number; i++)
{
answer[i] = Console.ReadLine();
}
case 2:
foreach (var item in answer)
{
Console.WriteLine(item.ToString());
}
break;
case 3:
Array.Sort(answer);
foreach (var item in answer)
{
Console.WriteLine(item.ToString());
}
break;
case 4:
Console.WriteLine("Are you sure you want to exit");
Console.WriteLine("1 for Yes and N for No");
y = (char)Console.Read();
if ((y == 1))
{
goto cases;
}
else
{
goto thankyou;
}
thankyou:
Console.WriteLine("thank you");
break;
}
Console.WriteLine("Are you sure you want to exit");
Console.WriteLine("Y for Yes and 1 for No");
y = (char)Console.Read();
if ((y == 1))
{
goto cases;
}
else
{
goto thankyou;
}
}
}
My problem is that after every operation I have ask whether it should continue or not. I have added go-to statements but when pressed No its shows an exception for input variable that I have declared.
Can I use the go-to method or Is there any way we can do this ?
Any suggestions what is wrong here??
If you want a loop in your program you should use one of the loop constructs in C#. In this case a while loop would work:
bool keepPrompting = true;
while(keepPrompting) {
Console.WriteLine("Enter the options given below 1.Add students\n 2.View all details\n 3.Sorting\n 4.Exit\n");
int input = Convert.ToInt16(Console.ReadLine());
// The case statement on input goes here
Console.WriteLine("Are you sure you want to exit");
Console.WriteLine("Y for Yes and 1 for No");
var y = (char)Console.Read();
if (y != 'y')
keepPrompting = false;
}
Console.WriteLine("thank you");
goto is almost never used in C# (or any other language) for that matter because it's hard to follow a program that can jump around to almost any location while a loop has a defined flow.
You shouldn't do this with goto. You should always avoid goto entirely. If you think for some reason that you need to use goto, you should find a way to do it without goto. Here's an example of how to do this while avoiding goto.
class Program
{
static void Main(string[] args)
{
int number;
dynamic y;
string[] answer = new string[10];
bool result = false;
while(!result) {
Console.WriteLine("Enter the options given below 1.Add students\n 2.View all details\n 3.Sorting\n 4.Exit\n");
int input = Convert.ToInt16(Console.ReadLine());
switch (input)
{
case 1:
Console.WriteLine("Enter the Number of Students to be added to the List");
number = Convert.ToInt16(Console.ReadLine());
for (int i = 0; i < number; i++)
{
answer[i] = Console.ReadLine();
}
break;
case 2:
foreach (var item in answer)
{
Console.WriteLine(item.ToString());
}
break;
case 3:
Array.Sort(answer);
foreach (var item in answer)
{
Console.WriteLine(item.ToString());
}
break;
case 4:
Console.WriteLine("Are you sure you want to exit");
Console.WriteLine("1 for Yes and N for No");
result = ((char)Console.Read()) == 'y';
break;
}
}
Console.WriteLine("thank you");
}
}
}
static void Main(string[] args)
{
// First you need a few loops, avoid goto's at all costs they make code much harder to read
// There are better ways to do this but this will get it done
// List<string> answer = new List<string>(); would be better here because it resizes automatically when adding
// I left it like this because it looks like a school project
List<string> answer = new List<string>(); // create variable before loops so it is not recreated on each iteration
bool exit = false; // create bool variable and use it to exit infinite loop by setting it to true when user chooses option 4
for (;;) // create outer infinit loop to so the code will execute until you want you break; when option 4 is entered
{
int option;
for (;;)// create infinite loop to get user input for which option they want
{
Console.Clear();
Console.WriteLine("Enter the options given below\n1.Add students\n2.View all details\n3.Sorting\n4.Exit\n");
if (int.TryParse(Console.ReadLine(), out option) && option >= 1 && option <= 4)
{ break; /*user entered valid option so we break from this infinit loop*/ }
else
{ Console.Clear(); /*User did not enter a valid option so clear the console window*/ }
}
switch (option) // switch cases to handle each of the possible options entered
{
case 1:
// user chose option 1
int number = 0;
while (number <= 0)
{
Console.Clear();
Console.WriteLine("Enter the number of students to add.");
int.TryParse(Console.ReadLine(), out number);
// Because "answer" is now a list it does not have to be sized
for(int i=0;i<number;i++)
{
Console.Clear();
Console.WriteLine("Enter Name: ");
// with a list, the previous list of students are not wiped out
// we also don't have to be carefull about writing outside array bounds because of the add method
answer.Add(Console.ReadLine());
}
}
break; // break out of case 1
case 2:
// user chose option 2
break;// break out of case 2
case 3:
// user chose option 3
if (answer.Count > 0)
{
Console.Clear();
Console.WriteLine("Sorted student names:");
answer.Sort(); // List<string> have a Sort member method
Console.WriteLine(string.Join("\n", answer));
}
else
{ Console.WriteLine("No students exist to sort or list."); }
Console.ReadLine(); // pause screen for reading
break;// break out of case 3
case 4:
// user chose option 4
while (true) // loop until a Y or 1 is entered
{
Console.WriteLine("Are you sure you want to exit\nY for YES and 1 for NO");
char y = (char)Console.Read();
if (y == 'Y' || y == 'y')
{ exit = true; break; /*user is sure they want to exit*/ }
else if (y == '1')
{ Console.Clear(); break; /*user decided not to exit*/ }
else
{ Console.Clear(); }
}
break; // break out of case 4
}
if (exit) break; // if exit variable true then break out of outer infinite loop
}
}
static void Main(string[] args)
{
// First you need a few loops, avoid goto's at all costs they make code much harder to read
// There are better ways to do this but this will get it done
// List<string> answer = new List<string>(); would be better here because it resizes automatically when adding
// I left it like this because it looks like a school project
string[] answer = new string[0]; // create variable before loops so it is not recreated on each iteration
bool exit = false; // create bool variable and use it to exit infinite loop by setting it to true when user chooses option 4
for (;;) // create outer infinit loop to so the code will execute until you want you break; when option 4 is entered
{
int option;
for (;;)// create infinite loop to get user input for which option they want
{
Console.Clear();
Console.WriteLine("Enter the options given below\n1.Add students\n2.View all details\n3.Sorting\n4.Exit\n");
if (int.TryParse(Console.ReadLine(), out option) && option >= 1 && option <= 4)
{ break; /*user entered valid option so we break from this infinit loop*/ }
else
{ Console.Clear(); /*User did not enter a valid option so clear the console window*/ }
}
switch (option) // switch cases to handle each of the possible options entered
{
case 1:
// user chose option 1
int number = 0;
while (number <= 0)
{
Console.Clear();
Console.WriteLine("Enter the number of students to add.");
int.TryParse(Console.ReadLine(), out number);
answer = new string[number]; // re-initize number of students to add
for(int i=0;i<number;i++)
{
Console.Clear();
Console.WriteLine("Enter Name: ");
answer[i] = Console.ReadLine();
}
}
break; // break out of case 1
case 2:
// user chose option 2
break;// break out of case 2
case 3:
// user chose option 3
if (answer.Length > 0)
{
Console.Clear();
Console.WriteLine("Sorted student names:");
Array.Sort(answer);
Console.WriteLine(string.Join("\n", answer));
Console.ReadLine(); // pause screen for reading
}
break;// break out of case 3
case 4:
// user chose option 4
while (true) // loop until a Y or 1 is entered
{
Console.WriteLine("Are you sure you want to exit\nY for YES and 1 for NO");
char y = (char)Console.Read();
if (y == 'Y' || y == 'y')
{ exit = true; break; /*user is sure they want to exit*/ }
else if (y == '1')
{ Console.Clear(); break; /*user decided not to exit*/ }
else
{ Console.Clear(); }
}
break; // break out of case 4
}
if (exit) break; // if exit variable true then break out of outer infinite loop
}
}

Collecting multiple Variables from one loop

I'm Working on a project for college and have sat here trying to figure out a solution to this problem for a solid 3 hours now. the problem is:
Scenario:
You want to calculate a student’s GPA (Grade Point Average) for a number of classes taken by the student during a single semester.
Inputs:
The student’s name.
Class names for the classes taken by the student.
Class letter grade for the classes taken by the student.
Class credit hours for the classes taken by the student.
Processing:
Accept and process classes until the user indicates they are finished.
Accumulate the number of credit hours taken by the student.
Calculate the total number of “points” earned by the student as:
a. For each class calculate the points by multiplying the credit hours for that class times the numeric equivalent of the letter grade. (A=4.0, B=3.0, C=2.0, D=1.0, F=0)
b. Total all points for all classes.
Calculate the GPA as the total number of “points” divided by the total credit hours.
Output:
Display a nicely worded message that includes the student’s name and the GPA (decimal point number with 2 decimal places) achieved by the student that semester.
What I currently have is:
static void Main(string[] args)
{
String StudentName;
//Error Trapping
try
{
Console.WriteLine("Welcome to The GPA Calculator");
Console.WriteLine("Hit any key to continue...");
Console.ReadKey();
Console.Write("Please enter your name: ");
StudentName = Convert.ToString(Console.ReadLine());
InputGradeInfo();
}
//Error Repsonse
catch (System.Exception e)
{
Console.WriteLine("An error has Occurred");
Console.WriteLine("The error was: {0}" , e.Message);
//Belittle the User
Console.WriteLine("Good Job, you Broke it.");
Console.ReadLine();
}
}
public static double InputGradeInfo()
{
String ClassName;
Char LetterGrade;
Double LetterGradeValue;
Double CreditHours;
Double ValueOfClass;
Console.Write("Please enter the class title: ");
ClassName = Convert.ToString(Console.ReadLine());
Console.Write("Please enter the total credits this class is worth: ");
CreditHours = Convert.ToDouble(Console.ReadLine());
Console.Write("Please enter the grade letter recived: ");
LetterGrade = Convert.ToChar(Console.ReadLine());
switch (LetterGrade)
{
case 'a': LetterGradeValue = 4;
break;
case 'A': LetterGradeValue = 4;
break;
case 'b': LetterGradeValue = 3;
break;
case 'B': LetterGradeValue = 3;
break;
case 'c': LetterGradeValue = 2;
break;
case 'C': LetterGradeValue = 2;
break;
case 'd': LetterGradeValue = 1;
break;
case 'D': LetterGradeValue = 1;
break;
case 'f': LetterGradeValue = 0;
break;
case 'F': LetterGradeValue = 0;
break;
default: LetterGradeValue = 0;
break;
}
ValueOfClass = CalculateClass(LetterGradeValue, CreditHours);
return ValueOfClass;
}
public static double CalculateClass(double LetterGrade, double CreditHours)
{
Double CreditTotal;
CreditTotal = CreditHours * LetterGrade;
return CreditTotal;
}
The Problem arises for me as to how one would loop info collection, save it to different variable every time and then breaking the loop using user input at the end. We haven't learned about arrays yet so that's off the table. After I have that looped collection down calculating the total GPA and displaying wouldn't be difficult.
Also I haven't learned about created classes yet so I can't use those either
static void Main(string[] args)
{
String StudentName;
//Error Trapping
try
{
Console.WriteLine("Welcome to The GPA Calculator");
Console.WriteLine("Hit any key to continue...");
Console.ReadKey();
Console.Write("Please enter your name: ");
StudentName = Convert.ToString(Console.ReadLine());
List<double> gradeInfoList = new List<double>();
List<double> creditList = new List<double>();
bool brakeLoop = false;
while (!brakeLoop)
{
gradeInfoList.Add(InputGradeInfo(creditList));
Console.WriteLine("Do you want to continue(y/n): ");
brakeLoop = Console.ReadLine() != "y";
}
Console.WriteLine(StudentName + " GPA is: " + gradeInfoList.Sum() / creditList.Sum());
}
//Error Repsonse
catch (System.Exception e)
{
Console.WriteLine("An error has Occurred");
Console.WriteLine("The error was: {0}", e.Message);
//Belittle the User
Console.WriteLine("Good Job, you Broke it.");
Console.ReadLine();
}
}
public static double InputGradeInfo(List<double> creditList)
{
String ClassName;
Char LetterGrade;
Double LetterGradeValue;
Double CreditHours;
Double ValueOfClass;
Console.Write("Please enter the class title: ");
ClassName = Convert.ToString(Console.ReadLine());
Console.Write("Please enter the total credits this class is worth: ");
CreditHours = Convert.ToDouble(Console.ReadLine());
creditList.Add(CreditHours);
Console.Write("Please enter the grade letter recived: ");
LetterGrade = Convert.ToChar(Console.ReadLine().ToUpper());
switch (LetterGrade)
{
case 'A': LetterGradeValue = 4;
break;
case 'B': LetterGradeValue = 3;
break;
case 'C': LetterGradeValue = 2;
break;
case 'D': LetterGradeValue = 1;
break;
case 'F': LetterGradeValue = 0;
break;
default: LetterGradeValue = 0;
break;
}
ValueOfClass = CalculateClass(LetterGradeValue, CreditHours);
return ValueOfClass;
}
public static double CalculateClass(double LetterGrade, double CreditHours)
{
Double CreditTotal;
CreditTotal = CreditHours * LetterGrade;
return CreditTotal;
}
Here you probably want this. You need one while loop to take all the classes, the loop brakes if you say that you don't want to continue or put another input. You make the gradeInfoList with gradeInfoList.Sum() function.
Also your variables should start with small letter, StudentName->studentName !
EDIT:
gpa List is collection which stores all your values which comes from InputGradeInfo().
What Sum() function is doing:
double sum = 0;
foreach(double d in gpa)
{
sum= sum + d; //(or sum+= d;)
}
In other words loop all the elements in gradeInfoList collection and make the sum of them.
About the while loop-> this loop will executes till the condition in the brackets is broken. In this case you can add many classes till you click 'y' at the end. If you click something else from 'y' you will break the loop.
I add another list creditList which you will add as parameter to the InputGradeInfo. In this list you will store every credit per class. At the end you will have gradeInfoList .Sum()/creditList.Sum() and this will give you what you want.

Case Switch with a loop

I am not understanding what is going on in my case statement to determine if I want to redo the users input. Should I make another loop outside of my while loop? I attempted such and my case statement becomes unreachable code. Maybe I am not understanding case-switch statements.
class Program
{
static void Main(string[] args)
{
string _a = "";
constructor con = new constructor();
Console.WriteLine("Enter enter exit to end the program...");
Console.WriteLine("Enter C for constructor, M for method, A for an array...");
Console.WriteLine("Please reference source code to have full details and understanding...");
bool control = true;
while (control)
{
_a = Console.ReadLine();
switch (_a.ToUpper())
{
case "EXIT":
Console.WriteLine("Thank you for using AJ's program...");
control = false;
break;
case "C":
Console.WriteLine(con.a);
Console.WriteLine("Would you like to test another scenario?");
Console.ReadLine();
if (_a.ToUpper() == "Y")
{
Console.ReadLine();
return;
}
control = false;
break;
case "M":
control = false;
metroid();
break;
case "A":
control = false;
Array();
break;
default: Console.WriteLine("No match");
break;
}
}
}
public class constructor
{
public string a = "This is a constructor!";
}
static public void metroid()
{
string b = "This is a method!";
Console.WriteLine(b);
}
static public void Array()
{
try
{
Console.WriteLine("This is a random array. Please enter the size.");
string sSize = Console.ReadLine();
int arraySize = Convert.ToInt32(sSize);
int[] size = new int[arraySize];
Random rd = new Random();
Console.WriteLine();
for (int i = 0; i < arraySize; i++)
{
size[i] = rd.Next(arraySize);
Console.WriteLine(size[i].ToString());
}
}
catch (System.FormatException)
{
Console.WriteLine("Not correct format, restarting array process.");
Array();
}
}
}
}
Here's what I came up with. You had too many ways of exiting your loop, so I removed all of the control = false lines except where the user typed "EXIT"
Also, in case "C" you return out of the method if they choose "Y", I changed that to continue so that the loop would continue.
Finally, I moved the 3 instruction statements into the loop, so when the user hit "Y" it would print those again.
static void Main(string[] args)
{
string _a = "";
constructor con = new constructor();
bool control = true;
while (control)
{
Console.WriteLine("Enter enter exit to end the program...");
Console.WriteLine("Enter C for constructor, M for method, A for an array...");
Console.WriteLine("Please reference source code to have full details and understanding...");
_a = Console.ReadLine();
switch (_a.ToUpper())
{
case "EXIT":
Console.WriteLine("Thank you for using AJ's program...");
control = false;
break;
case "C":
Console.WriteLine(con.a);
Console.WriteLine("Would you like to test another scenario?");
_a = Console.ReadLine(); //<==problem #1 you didnt set your var name
if (_a.ToUpper() == "Y")
{
continue; //<==problem #2 return exits the program, continue, just keeps going
}
control = false;
break;
case "M":
metroid();
break;
case "A":
Array();
break;
default:
Console.WriteLine("No match");
break;
}
}
}
I think you should considering goto in this case. Yes you need to put some extra effort, but it will help you overcoming the While loop.
A sample below:
switch (_a.ToUpper())
{
case "EXIT":
Console.WriteLine("Thank you for using AJ's program...");
control = false;
// execute goto when your all line executes successfully
goto case "New";
case "New":
// some logic
}
See working sample here Goto-Switch
string NewInput= Console.ReadLine();
if (NewInput.ToUpper() == "Y")
{
//print some thing with console.writeline
//if after this you want to restart the loop then instead of return use
continue;
}
Try putting the Console.Writeline inside the while loop like this:
static void Main(string[] args)
{
bool control = true;
while (control)
{
Console.WriteLine("Enter enter exit to end the program...");
Console.WriteLine("Enter C for constructor, M for method, A for an array...");
Console.WriteLine("Please reference source code to have full details and understanding...");
string _a = Console.ReadLine();
switch (_a.ToUpper())
{
case "EXIT":
Console.WriteLine("Thank you for using AJ's program...");
control = false;
break;
case "C":
Console.WriteLine("press c");
Console.WriteLine("Would you like to test another scenario?");
Console.ReadLine();
if (_a.ToUpper() == "Y")
{
Console.ReadLine();
return;
}
control = false;
break;
case "M":
control = false;
metroid();
break;
case "A":
control = false;
Array();
break;
default: Console.WriteLine("No match");
break;
}
}
}
Additional reading about switch here and here.
Just add comment for the result, thanks. Hope this helped!
may be you want to change
Console.ReadLine();
if (_a.ToUpper() == "Y")
{
Console.ReadLine();
return;
}
as
_a = Console.ReadLine();
if (_a.ToUpper() == "Y")
{
_a = Console.ReadLine();
continue;
}

Categories