Why won't enum trigger the default option? - c#

EDIT:
The program still does not work as it is supposed to. I tried to implement the suggested changes, which seemed to be the solution indeed. However, now any input into the programme leads to the default statement. What are we doing wrong?
NEW CODE WITH CHANGES BELOW:
public class Processor
{
public void DisplayEmployers()
{
Console.WriteLine("Select an option");
Console.WriteLine("1. Lawyer");
Console.WriteLine("2. Admin");
Console.WriteLine("3. Receptionist");
Console.ReadLine();
}
public enum Staff { Lawyer, Admin, Receptionist, UnsupportedValue }
public void ChooseTypeOfEmployer()
{
Staff s = (Staff.UnsupportedValue);
switch (s)
{
case Staff.Lawyer:
ProvideLogin();
break;
case Staff.Admin:
ProvideLogin();
break;
case Staff.Receptionist:
ProvideLogin();
break;
default:
Console.WriteLine("Invalid input");
break;
}
}
public void ProvideLogin()
{
string username, password;
Console.WriteLine("Please provide username to access the system");
{
Console.WriteLine("Input a username: ");
username = Console.ReadLine();
Console.WriteLine("Input as password: ");
password = Console.ReadLine();
{

Because you already handled all available values.
Try the next case:
public enum Staff { Lawyer, Admin, Receptionist, UnsupportedValue }
public void ChooseTypeOfEmployer()
{
Staff s = (Staff.UnsupportedValue);
switch (s)
{
case Staff.Lawyer:
ProvideLogin();
break;
case Staff.Admin:
ProvideLogin();
break;
case Staff.Receptionist:
ProvideLogin();
break;
default:
Console.WriteLine("Invalid input");
break;
}
}
++ you may to simplify you code
public void ChooseTypeOfEmployer()
{
Staff s = (Staff.UnsupportedValue);
switch (s)
{
case Staff.Lawyer:
case Staff.Admin:
case Staff.Receptionist:
ProvideLogin();
break;
default:
Console.WriteLine("Invalid input");
break;
}
}

Related

Public Int Error

I am trying to create a menu that goes to different sections without using a class but I am receiving errors using public int.
public int menu()
Console.WriteLine("Select a category to view");
Console.WriteLine("");
Console.WriteLine("1.Groceries");
Console.WriteLine("2.Electronics & Appliances");
Console.WriteLine("3.Exit");
Console.ReadKey();
int User = int.Parse(Console.ReadLine());
switch (User)
{
case 1:
Console.WriteLine("...........Groceries...............");
break;
case 2:
Console.WriteLine("..............Electronics & Appliances............");
break;
case 3:
Console.WriteLine("...........Exit...............");
break;
}
Turning your function into a static void method solves the problem. And you are missing the { after the menu(). Following your paradigm the code would be:
namespace ConsoleApplication1
{
class Program
{
static void menu()
{
Console.WriteLine("Select a category to view");
Console.WriteLine("");
Console.WriteLine("1.Groceries");
Console.WriteLine("2.Electronics & Appliances");
Console.WriteLine("3.Exit");
Console.ReadKey();
int User = int.Parse(Console.ReadLine());
switch (User)
{
case 1:
Console.WriteLine("...........Groceries...............");
break;
case 2:
Console.WriteLine("..............Electronics & Appliances............");
break;
case 3:
Console.WriteLine("...........Exit...............");
break;
}
}
static void Main(string[] args)
{
menu();
}
}
}

Wrong override called?

I'm new to programming and this class-things are doing my head in.
Here is my code (type is based on userinput)
public static Account CreateAccount(int type)
{
switch (type)
{
case 1:
SaveAcc savings = new SaveAcc();
break;
default:
Console.WriteLine("No such choice");
break;
}
return new Account();
}
These are my classes:
class Account
{
protected int balance;
protected int accountnr = 1;
protected bool credit;
public Account()
{
newNr++;
accountnr = newNr;
}
public override string ToString()
{
return "AccNr: " + Nr.ToString("G") + ", balance: " + balance.ToString("C");
}
}
class SaveAcc: Account
{
public int rate;
public SaveAcc()
{
credit = true;
rate = 0.03;
}
public override string ToString()
{
return "AccNr: " + Nr.ToString("G") + ", balance: " + balance.ToString("C") + credit.ToString();
}
}
When I create a SavAcc object the "wrong" override is being called. My goal is to display all the information given by the override ToString method located in the SavAcc inherited class. Am I missing something obvious?
Change this:
switch (type)
{
case 1:
SaveAcc savings = new SaveAcc();
break;
default:
Console.WriteLine("No such choice");
break;
}
return new Account();
To this:
switch (type)
{
case 1:
return new SaveAcc();
default:
Console.WriteLine("No such choice");
return new Account();
}

How to test methods involving strings in C#

I have an app which allows you to add student and lecturer details, and search them, and display them, etc. This is for a college assignment, and I have to test five of the methods I have created. Firstly, I'm not sure how to test a method involving strings, as all the testing methods I have seen involved a bank account app, and testing withdrawal and deposit methods seems easy as you just have to add and subtract numbers. I'm not sure at all how to test my, (for example) AddLecturer() method. I've tried to get one of the methods to throw an exception if a Status class that I created is entered correctly, but the program seems to still consider it an unhandled exception. How do I fix the exception so it's handled correctly, and how do I test these other methods?
Here's the main entry point to the app with all the methods.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DBSManagement
{
public class College: Staff
{
public static List<Student> students = new List<Student>();
public static List<Lecturer> lecturers = new List<Lecturer>();
public static void Main()
{
int choice;
bool seeAgain = true;
do
{
Console.WriteLine("Press");
Console.WriteLine("1: To add a student");
Console.WriteLine("2: To add a lecturer");
Console.WriteLine("3: To search for a lecturer or student");
Console.WriteLine("4: To show the details of all enrolled students");
Console.WriteLine("5: To show the names of all lecturers");
Console.WriteLine("6: To show payroll details for a lecturer");
Console.WriteLine("7: To quit");
int.TryParse(Console.ReadLine(), out choice);
switch (choice)
{
case 1:
AddStudent();
break;
case 2:
AddLecturer();
break;
case 3:
SearchPerson();
break;
case 4:
ShowStudents();
break;
case 5:
ShowLecturers();
break;
case 6:
ShowPayrollDetails();
break;
case 7:
seeAgain = false;
break;
default:
Console.WriteLine("Invalid option selected");
break;
}
} while (seeAgain);
}
public static void AddStudent()
{
Student student = new Student();
Console.WriteLine("Enter student name:");
if (Console.ReadLine() != null)
{
student.Name = Console.ReadLine();
}
else throw new ArgumentNullException("Please enter a name");
Console.WriteLine("Enter student address:");
student.Address = Console.ReadLine();
Console.WriteLine("Enter student phone number:");
student.Phone = Console.ReadLine();
Console.WriteLine("Enter student email:");
student.Email = Console.ReadLine();
Console.WriteLine("Enter student PPSN:");
student.PPSN = Console.ReadLine();
Console.WriteLine("Enter student status (postgrad or undergrad):");
EnterStat:
string stat = Console.ReadLine().ToLower();
if (stat == "postgrad" || stat == "undergrad")
{
student.Status = (Status)Enum.Parse(typeof(Status), stat);
}
else
{
Console.WriteLine("Please enter either postgrad or undergrad:");
goto EnterStat;
}
Console.WriteLine("Enter student ID:");
int inStudentID;
int.TryParse(Console.ReadLine(), out inStudentID);
student.StudentID = inStudentID;
students.Add(student);
}
public static void AddLecturer()
{
Lecturer lecturer = new Lecturer();
Console.WriteLine("Enter lecturer name:");
lecturer.Name = Console.ReadLine();
Console.WriteLine("Enter lecturer address:");
lecturer.Address = Console.ReadLine();
Console.WriteLine("Enter lecturer phone number:");
lecturer.Phone = Console.ReadLine();
Console.WriteLine("Enter lecturer email:");
lecturer.Email = Console.ReadLine();
Console.WriteLine("Enter lecturer PPSN:");
lecturer.PPSN = Console.ReadLine();
Console.WriteLine("Enter lecturer ID:");
lecturer.ID = Console.ReadLine();
Console.WriteLine("Enter salary:");
lecturer.Salary = decimal.Parse(Console.ReadLine());
Console.WriteLine("Enter subject taught:");
lecturer.SubjectTaught = Console.ReadLine().ToLower();
lecturers.Add(lecturer);
}
public static void SearchPerson()
{
int searchChoice = 0;
int studentSearch = 0;
int lecturerSearch = 0;
Console.WriteLine("Press:");
Console.WriteLine("1 to search for a student");
Console.WriteLine("2 to search for a lecturer");
int.TryParse(Console.ReadLine(), out searchChoice);
switch (searchChoice)
{
//search students
case 1:
Console.WriteLine("Press:");
Console.WriteLine("1 to search by name");
Console.WriteLine("2 to search by student number");
int.TryParse(Console.ReadLine(), out studentSearch);
switch (studentSearch)
{
case 1:
Console.WriteLine("Enter student name:");
string studentNameSearch = Console.ReadLine();
bool sFound = false;
foreach (Student student in students)
{
if (student.Name.Contains(studentNameSearch))
{
Console.WriteLine(student.ToString());
sFound = true;
break;
}
}
if (sFound == false)
{
Console.WriteLine("Student name not found");
}
break;
case 2:
int studentIDSearch;
bool IDFound = false;
Console.WriteLine("Enter student number:");
int.TryParse(Console.ReadLine(), out studentIDSearch);
foreach (Student student in students)
{
if (student.StudentID.Equals(studentIDSearch))
{
Console.WriteLine(student.ToString());
IDFound = true;
break;
}
}
if (IDFound == false)
{
Console.WriteLine("Student name not found");
}
break;
default:
Console.WriteLine("Invalid option selected");
break;
}
break;
//search lecturers
case 2:
Console.WriteLine("Press:");
Console.WriteLine("1 to search by name");
Console.WriteLine("2 to search by course taught");
int.TryParse(Console.ReadLine(), out lecturerSearch);
switch (lecturerSearch)
{
case 1:
Console.WriteLine("Enter lecturer name:");
string lecturerNameSearch = Console.ReadLine();
bool lFound = false;
foreach (Lecturer lecturer in lecturers)
{
if (lecturer.Name.Contains(lecturerNameSearch))
{
Console.WriteLine(lecturer.ToString());
lFound = true;
break;
}
}
if (lFound == false)
{
Console.WriteLine("Lecturer name not found");
}
break;
case 2:
Console.WriteLine("Enter course taught:");
string lecturerSubjectSearch = Console.ReadLine().ToLower();
bool subjectFound = false;
foreach (Lecturer lecturer in lecturers)
{
if (lecturer.SubjectTaught.Contains(lecturerSubjectSearch))
{
Console.WriteLine(lecturer.ToString());
subjectFound = true;
break;
}
}
if (subjectFound == false)
{
Console.WriteLine("Subject not found");
}
break;
default:
Console.WriteLine("Invalid option selected");
break;
}
break;
default:
Console.WriteLine("Invalid option selected");
break;
}
}
public static void ShowStudents()
{
//sort list by name
List<Student> SortedStudents = students.OrderBy(o => o.Name).ToList();
foreach (Student student in SortedStudents)
{
Console.WriteLine(student);
}
}
public static void ShowLecturers()
{
//sort list by name
List<Lecturer> SortedLecturers = lecturers.OrderBy(o => o.Name).ToList();
foreach (Lecturer lecturer in SortedLecturers)
{
Console.WriteLine(lecturer.Name);
}
}
public static void ShowPayrollDetails()
{
Console.WriteLine("Enter lecturer name:");
string lecturerNameSearch = Console.ReadLine();
for (int i = 0; i < lecturers.Count; i++)
{
if (lecturers[i].Name == lecturerNameSearch)
{
Console.WriteLine(lecturers[i].PayrollDetails());
}
else
{
Console.WriteLine("Lecturer name not found");
}
}
}
}
}
Here are the test methods I have created so far.
using Microsoft.VisualStudio.TestTools.UnitTesting;
using DBSManagement;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DBSManagement.Tests
{
[TestClass()]
public class CollegeTests
{
[TestMethod()]
[ExpectedException(typeof(ArgumentException))]
public void AddStudentTest()
{
//arrange
string s = "student";
Status status = (Status)Enum.Parse(typeof(Status), s);
//act
Student student1 = new Student("Name", "123 Fake St", "0851234567", "fake#address.com", "7895459R", status, 12345678);
//assert
//handled by exception
}
[TestMethod()]
public void AddLecturerTest()
{
Assert.Fail();
}
[TestMethod()]
public void SearchPersonTest()
{
Assert.Fail();
}
[TestMethod()]
public void ShowStudentsTest()
{
Assert.Fail();
}
[TestMethod()]
public void ShowLecturersTest()
{
Assert.Fail();
}
[TestMethod()]
public void ShowPayrollDetailsTest()
{
Assert.
This is the student class. I'm attempting to make it throw an exception if anyone enters a status other than postgrad or undergrad. These are enums.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DBSManagement
{
public class Student : Person
{
private Status status;
//auto-implemented properties
public Status Status
{
get
{
return status;
}
set
{
if (value == Status.undergrad || value == Status.postgrad)
{
status = value;
}
else throw new ArgumentException("Error: please select undergrad or postgrad");
}
}
public int StudentID { get; set; }
//empty constructor
public Student() { }
//constructor with parameters
public Student(string name, string address, string phone, string email, string ppsn, Status status, int studentId)
:base(name, address, phone, email, ppsn)
{
Status = status;
StudentID = studentId;
}
//overridden ToString() method
public override string ToString()
{
return string.Format("Name: {0}\nStudent Number: {1}\nAddress: {2}\nPhone: {3}\nEmail: {4}\nStatus: {5}",
Name, StudentID, Address, Phone, Email, Status);
}
}
}
You can test your code, but these tests will be very fragile (and, as #Scott Chamberlain noted, it won't be clear what they will be proving).
What you need to do is to "hide" that ugly Console.ReadLine() behind something you have "programmatic" control over. Func<string> would be ideal:
public static void AddStudent(Func<string> consoleReader)
{
Student student = new Student();
Console.WriteLine("Enter student name:");
student.Name = Console.ReadLine();
// ...
}
With this, your tests become something like:
[Test]
void TestAddStudent()
{
var n = 0;
var strings = new[] {
"Name",
"123 Fake St",
"0851234567",
"fake#address.com",
"7895459R",
// ...
};
Func<string> consoleReader = () => strings[n++];
var student = AddStudent(consoleReader);
Assert.AreEqual(strings[0], student.Name);
// ...
}
If you want to do testing it would be easier if you separate your UI from the logic. You could for instance adopt a MVC pattern or something like that. Start by building all your data objects like Lecturer, Student, etc. These objects would be your data model. Then add the logic, or controls, which manipulate these data objects. There could be a AddLecturer(..) method in the control component. Finally make a UI, or view, which interacts with them without being fully intertwined like in your code. With regard to testing, you'll mainly be writing tests for methods in the control components and maybe the model. There are plenty of things to test. Take your add lecturer method:
Is the name longer than 3 characters?
Is there at least two names? (Maybe this is a too strong assumption?)
Is the phone number correctly formatted?
Is the e-mail correctly formatted?
Is the lecturer ID only numbers? (Although, I'd expect the lecturer ID is something generated by your system)
Is the PPSN well formatted?
Is the salary positive?
Is the salary under a ludicrously large amount?
Is the salary even a number?`
When adding a new lecturer to lecturers did it really get added? (Typically you'd never check this. We trust the basic collections, unless you wrote it yourself.)
etc.

C# - The name 'BoyorGirl' does not exist in the current context

I'm trying to create a text adventure in C#, it's very different from XNA coding, I am triying to display the gender of the player, but it's in a different field. I get this error:
The name 'BoyorGirl' does not exist in the current context
(The error is at line 113, column 73).
And this is the script: (I put a // where the error appears)
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
....
Console.WriteLine("\t\t Press Enter to continue...");
Console.ReadLine();
Console.Clear();
Start_Game();
}
static public void Start_Game()
{
int StartMenu;
Console.WriteLine(#"Welcome Adventurer..
Are you ready for an adventure?
#1 Start Game
#2 Help
#3 Exit");
StartMenu = int.Parse(Console.ReadLine());
switch (StartMenu)
{
case 1:
Start_Adventure();
break;
case 2:
Help_Menu();
break;
case 3:
Console.WriteLine("Goodbye.");
System.Threading.Thread.Sleep(1000);
Environment.Exit(0);
break;
default:
Console.WriteLine("This is not an option..");
System.Threading.Thread.Sleep(2000);
Console.Clear();
Start_Game();
break;
}
}
static public void Start_Adventure()
{
Console.Clear();
Console.WriteLine("You're a normal..\nBoy/Girl?");
string BoyorGirl;
BoyorGirl = Console.ReadLine();
BoyorGirl = BoyorGirl.ToLower();
switch (BoyorGirl)
{
case "boy":
BoyorGirl = "Boy";
Console.Clear();
input_name();
break;
case "girl":
BoyorGirl = "Girl";
Console.Clear();
input_name();
break;
default:
Console.WriteLine("This is not an option..");
System.Threading.Thread.Sleep(2000);
Console.Clear();
Start_Adventure();
break;
}
}
public static void input_name()
{
Console.WriteLine("You're just a normal {0}, called.. input your name please.");
string name;
name = Console.ReadLine();
Console.Clear();
Console.WriteLine("You're just a normal {0}, called {1}..", BoyorGirl, name); //The error appears here.
}
static public void Help_Menu()
{
}
}
}
I also want to get rid of the statics, but I don't think that's possible. Any idea on how to fix this?
That variable only exists in the scope of the Start_Adventure() method.
If you want to use it in that method, you need to either delcare it globally or pass it into the method.
public static void input_name(string BoyorGirl)
{
//Do Work Here
}
OR
namespace ConsoleApplication1
{
class Program
{
private static string BoyOrGirl;
...
if you go with the second option, remember to remove this
string BoyorGirl;
from Start_Adventure()
Because BoyorGirl is a local variable to your Start_Adventure method. You need to pass that variable if you want to use it:
BoyorGirl = "Girl";
Console.Clear();
input_name(BoyorGirl);
// ....
public static void input_name(string BoyorGirl) {
}
Change your code to following:
static public void Start_Adventure()
{
...
input_name(BoyorGirl);
...
}
public static void input_name(string BoyorGirl)
{
Console.WriteLine("You're just a normal {0}, called.. input your name please.");
string name;
name = Console.ReadLine();
Console.Clear();
Console.WriteLine("You're just a normal {0}, called {1}..", BoyorGirl, name); //The error appears here.
}
The string BoyorGirl was not known in your input_name-method.
So you have to pass the string to the method or use a global var.
You defined the variable BoyorGirl in the scope of the method Start_Adventure(), it will not be available outside of that scope.
Therefore, you have to either change the variable to be a member of the class Program, or pass it to the input_name() method as an argument.
A variable declared inside a method is local to that specific method and cannot be accessed from elsewhere. As such, input_name has no idea what BoyorGirl is, because it's only found in Start_Adventure.
What you could do is to pass the variable to input_name:
public static void input_name(string BoyorGirl)
and
input_name(BoyorGirl);

Classes with String Switches

class AddItemOption
{
//Fields that contain class data
string input = Console.ReadLine();
//Methods that define class functionality
public string myFunction(string Value)
{
switch (input)
{
case "Umbrella":
Console.WriteLine("Umbrella is selected");
break;
case "Rain Coat":
Console.WriteLine("Raincoat is selected");
break;
case "Boots":
Console.WriteLine("Boots is selected");
break;
case "Hood":
Console.WriteLine("Hood is selected");
break;
default:
Console.WriteLine("Input not reconized, please choose another item");
break;
}
}
I get the error "Not all code paths return a value". It is from myFunction(string Value). I'm not sure how to return this, or what to put in the parameter to get it to work. Do I need something below it too? I am new to classes. Please tell me if I'm doing this all wrong or if that is where the switch statement should go!
public AddItemOption(string input)
{
}
FROM Shyju I changed it to:
class AddItemOptionOne
{
//Fields that contain class data
string input = Console.ReadLine();
//Methods that define class functionality
public string myFunction(string Value)
{
switch (input)
{
case "Key Chain":
return "Key Chain is selected";
break;
case "Leather Armor":
return "Leather Armor is selected";
break;
case "Boots":
return "Boots is selected";
break;
case "Sword":
return "Sword is selected";
break;
default:
return "Input not reconized, please choose another item";
break;
}
}
However, it does not recognize the breaks. "Unreachable Code Detected"
Your method has a return type of string. That means your method should always return some string. But you are not returning a string. instead you are Writing it to the console using WriteLine method.
So Change
Console.WriteLine("Umbrella is selected");
to
return "Umbrella is selected";
OR
You can change your method's return type to void.
public void myFunction(string Value)
{
//your current fancy stuff here
Console.WriteLine("My method dont have a return type");
}
EDIT : AS per the question edit.
return statement will take the control out from your method. that means the next line (break) won't be executed. So remove the break statement.
case "Key Chain":
return "Key Chain is selected";
Well... You don't return anything from your function, so change it to
public void myFunction(string Value)
Try this:
class AddItemOptionOne
{
//Methods that define class functionality
public string myFunction(string input)
{
string result = string.Empty;
switch (input)
{
case "Key Chain":
result = "Key Chain is selected";
break;
case "Leather Armor":
result = "Leather Armor is selected";
break;
case "Boots":
result = "Boots is selected";
break;
case "Sword":
result = "Sword is selected";
break;
default:
result = "Input not reconized, please choose another item";
break;
}
return result;
}
}

Categories