Public Int Error - c#

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

Related

Why won't enum trigger the default option?

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

My C# code on Visual Studio 2013 doesn't work properly

I am trying to be an educated lazy chemistry student, by making a C# program that can do chemistry calculation for me. In order to make the code, I have to understand well the procedures in chemistry class.
I am new to any kind of programming, C# is my first language.
The code works fine for 1 Element calculation, but not 2 Elements calculation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
MassCalculation myMassCalculation = new MassCalculation();
TwoMassCalculation myTwoMassCalculation = new TwoMassCalculation();
Console.WriteLine("How many elements are in the compound?");
string userMainInput = Console.ReadLine();
if (userMainInput == "1")
{
myMassCalculation.Amount1 = 1;
Console.WriteLine("What is the ELEMENT?");
string userInput1 = Console.ReadLine();
Elements element;
if (Enum.TryParse<Elements>(userInput1, true, out element))
{
switch (element)
{
case Elements.Na:
myMassCalculation.Element1 = 22.990;
break;
case Elements.Cl:
myMassCalculation.Element1 = 35.453;
break;
default:
break;
}
}
Console.WriteLine("How many?");
string userAmount1 = Console.ReadLine();
int myAmount1 = int.Parse(userAmount1);
myMassCalculation.Amount1 = myAmount1;
myMassCalculation.DoCalculation();
resultOfMassCalculation(myMassCalculation);
}
if (userMainInput == "2")
{
Console.WriteLine("What is the First ELEMENT?");
string userInput1 = Console.ReadLine();
Elements element;
if (Enum.TryParse<Elements>(userInput1, true, out element))
{
switch (element)
{
case Elements.Na:
myMassCalculation.Element1 = 22.990;
break;
case Elements.Cl:
myMassCalculation.Element1 = 35.453;
break;
default:
break;
}
}
Console.WriteLine("How many?");
string userAmount1 = Console.ReadLine();
int myAmount1 = int.Parse(userAmount1);
myMassCalculation.Amount1 = myAmount1;
Console.WriteLine("What is the Second ELEMENT?");
string userInput2 = Console.ReadLine();
if (Enum.TryParse<Elements>(userInput2, true, out element))
{
switch (element)
{
case Elements.Na:
myTwoMassCalculation.Element2 = 22.990;
break;
case Elements.Cl:
myTwoMassCalculation.Element2 = 35.453;
break;
default:
break;
}
}
Console.WriteLine("How many?");
string userAmount2 = Console.ReadLine();
int myAmount2 = int.Parse(userAmount2);
myTwoMassCalculation.Amount2 = myAmount2;
myTwoMassCalculation.DoCalculation();
resultOfMassCalculation(myTwoMassCalculation);
}
Console.ReadLine();
}
private static void resultOfMassCalculation(MassCalculation calculation)
{
Console.Write("The Mass is {0}g/mol", calculation.DoCalculation());
}
}
enum Elements
{
Na,
Cl,
}
class MassCalculation
{
public double Element1 { get; set; }
public int Amount1 { get; set; }
public virtual double DoCalculation()
{
double result = Element1 * Amount1;
return result;
}
}
class TwoMassCalculation : MassCalculation
{
public double Element2 { get; set; }
public int Amount2 { get; set; }
public override double DoCalculation()
{
double result = Element1 * Amount1 + Element2 * Amount2;
return result;
}
}
}
Please help! I know it seems somewhat unprofessional. I have just started programming a week ago, and this is the best I can do. I need guidance.
The only elements defined in the code is Na and Cl, I am trying to calculate NaCl. When everything is in place, I will add more elements to the list, and many more different types of calculations.
I'll take constructive opinions.
Thank you so much in advance.
I refactored your code a little. It will work the same way, but wont crash on inappropriate user input
https://dotnetfiddle.net/CMQugr
using System;
using System.Collections.Generic;
namespace Test
{
public class Program
{
public static Dictionary<string, double> Elements = new Dictionary<string, double>
{
{"Na",22.990},
{"Cl",35.453}
};
public static void Main()
{
double result = 0;
int elemenCountInput;
do
{
Console.WriteLine("How many elements are in the compound?");
} while (!Int32.TryParse(Console.ReadLine(), out elemenCountInput));
for (int i = 0; i < elemenCountInput; i++)
{
string element;
do
{
Console.WriteLine("What is the {0} element", (i + 1));
element = Console.ReadLine();
} while (!Elements.ContainsKey(element));
int amount;
do
{
Console.WriteLine("How many");
} while (!Int32.TryParse(Console.ReadLine(), out amount));
result += Elements[element] * amount;
}
Console.Write("The Mass is {0}g/mol", result);
Console.ReadLine();
}
}
}
There is problem in the code when elements are two. You are assigning the first element value to "myMassCalculation' object and second element value to "myTwoMassCalculation". When you call "DoCalculation()" "myTwoMassCalculation.Element1' and "myTwoMassCalculation.Amount1" have no values. That's why it is giving wrong answer. Make the following changes and try:
if (Enum.TryParse<Elements>(userInput1, true, out element))
{
switch (element)
{
case Elements.Na:
myTwoMassCalculation.Element1 = 22.990;
break;
case Elements.Cl:
myTwoMassCalculation.Element1 = 35.453;
break;
default:
break;
}
}
Console.WriteLine("How many?");
string userAmount1 = Console.ReadLine();
int myAmount1 = int.Parse(userAmount1);
myTwoMassCalculation.Amount1 = myAmount1;
I'd do something like:
Create a class for elements (name (string), whatever that number is (double/decimal)
Create a static dictionary of them of them indexed by name.
Loop through the parameters to Main (or loop around an input command) looking up each entry in the dictionary then perform the calculation.
Convert to LINQ if desired.
This is be a great approach and should teach you a lot. I'm not going to write it for you (time and desire), but I may come back later with an example.

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

I need a simple and elegant user validation technique for a c# console application

Coming from a procedural background, I'm running into a conceptual block while designing a menu-based console application and user input validation. My goal is to display a menu that launches other processes. I want to limit user input to 1, 2, or 3 at the menu.
In a procedural language, I would do something like this pseudocode:
10 print "Make a choice"
20 choice = [dataFromKeyboard]
30 if choice < 4 && choice > 0
40 then 10
50 else 60
60 process valid choices
and no matter what I try, I can't get that out of my head while designing an OO program. Consider (simplified to include only 3 menu items):
class Menu
{
public static void Main(String[] args)
{
DisplayMenu thisdm = new DisplayMenu;
int menuChoice = thisdm.displayMenu();
ProcessMenu thispm = new ProcessMenu();
thispm.processMenu(menuChoice);
}
}
class DisplayMenu
{
public int displayMenu()
{
Console.WriteLine("1 - foo3");
Console.WriteLine("2 - foo2");
Console.WriteLine("3 - foo3");
Console.WriteLine("choose");
String choice = Console.ReadLine();
int intChoice = Convert.ToInt32(choice);
return intChoice;
}
}
class ProcessMenu
{
public void processMenu(int choice)
{
switch(choice)
{
case 1:
foo1();
break;
case 2:
foo2();
break;
case 3:
foo3();;
break;
default:
Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
break;
}
}
}
So here's where I'm stuck. I just can't wrap my head around a simple and elegant way validate my user input that's from an OO rather than procedural standpoint.
Assuming I do the validation in the DisplayMenu, I would be validating after the input is read. But if it turns out to be invalid, how do I re-ask for valid input, since I've already called displayMenu method from Main?
I've been playing with while loops for about an hour, something like this:
intChoice = 0;
[print the menu]
while ((intChoice<1) || (intChoice>3))
Console.WriteLine("Please make a valid choice from the menu");
choice = Console.ReadLine();
etc.
but can't seem to find the sweet spot where I can control user input.
I suspect it's because I'm thinking to procedurally, and not object-oriented enough. Anyone have any tips or input to help me wrap my head around this?
Expanding on #AlexeiLevenkov's suggestion of "turning your classes 90 degrees", I went a step further and created this example of a "Modular" console Application:
class Program
{
static void Main(string[] args)
{
//Retrieve all Module types in the current Assembly.
var moduletypes = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(x => x.IsSubclassOf(typeof(ConsoleModule)));
//Create an instance of each module
var modules = moduletypes.Select(Activator.CreateInstance)
.OfType<ConsoleModule>()
.OrderBy(x => x.Id)
.ToList();
int SelectedOption = -1;
while (SelectedOption != 0)
{
//Show Main Menu
Console.Clear();
Console.WriteLine("Please Select An Option:\n");
modules.ForEach(x => Console.WriteLine(string.Format("{0} - {1}", x.Id, x.DisplayName)));
Console.WriteLine("0 - Exit\n");
int.TryParse(Console.ReadLine(), out SelectedOption);
//Find Module by Id based on user input
var module = modules.FirstOrDefault(x => x.Id == SelectedOption);
if (module != null)
{
//Execute Module
Console.Clear();
module.Execute();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
}
}
}
ConsoleModule class:
public abstract class ConsoleModule
{
public int Id { get; set; }
public string DisplayName { get; set; }
public abstract void Execute();
}
Some sample Modules:
public class EnterUserNameModule : ConsoleModule
{
public EnterUserNameModule()
{
Id = 2;
DisplayName = "User Name";
}
public static string UserName { get; set; }
public override void Execute()
{
Console.WriteLine("Please Enter Your Name: ");
UserName = Console.ReadLine();
}
}
public class HelloWorldModule: ConsoleModule
{
public HelloWorldModule()
{
Id = 1;
DisplayName = "Hello, World!";
}
public override void Execute()
{
Console.WriteLine("Hello, " + (EnterUserNameModule.UserName ?? "World") + "!");
}
}
public class SumModule: ConsoleModule
{
public SumModule()
{
Id = 3;
DisplayName = "Sum";
}
public override void Execute()
{
int number = 0;
Console.Write("Enter A Number: ");
if (int.TryParse(Console.ReadLine(), out number))
Console.WriteLine("Your number plus 10 is: " + (number + 10));
else
Console.WriteLine("Could not read your number.");
}
}
Result:
It uses a little bit of reflexion to find all types deriving from ConsoleModule in the current assembly, then shows a menu with all these options (which are actually properties in this class), and calls the Execute() method when an appropiate option is selected. Much more towards OO way of thinking.
Make your processMenu function return some kind of indicator. You could use exceptions for this instead, but that's overkill.
public bool processMenu(int choice)
{
....
}
If the choice was acceptable, then return true, otherwise return false. Then:
public static void Main(String[] args)
{
DisplayMenu thisdm = new DisplayMenu;
ProcessMenu thispm = new ProcessMenu();
int menuChoice;
do {
menuChoice = thisdm.displayMenu();
} while( !thispm.processMenu(menuChoice) );
}
The way you are doing should be changed. Anyhow, for the same as your question, this works out:
DisplayMenu thisdm = new DisplayMenu();
int menuChoice = -1;
while (menuChoice < 1 || menuChoice > 3)
{
Console.WriteLine("enter valid choice");
menuChoice = thisdm.displayMenu();
}
ProcessMenu thispm = new ProcessMenu();
thispm.processMenu(menuChoice);
the code like:
class Program
{
static void Main(string[] args)
{
DisplayMenu thisdm = new DisplayMenu();
ProcessMenu thispm = new ProcessMenu();
thisdm.displayMenu();
int menuChoice = thispm.GetChoice();
thispm.processMenu(menuChoice);
Console.Read();
}
}
class DisplayMenu
{
public void displayMenu()
{
Console.WriteLine("1 - foo3");
Console.WriteLine("2 - foo2");
Console.WriteLine("3 - foo3");
Console.WriteLine("choose");
}
}
class ProcessMenu
{
public int GetChoice()
{
String choice = Console.ReadLine();
int intChoice = Convert.ToInt32(choice);
while (!Validate(intChoice))
{
Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
choice = Console.ReadLine();
intChoice = Convert.ToInt32(choice);
}
return intChoice;
}
public void processMenu(int choice)
{
switch (choice)
{
case 1:
//foo1();
break;
case 2:
//foo2();
break;
case 3:
//foo3(); ;
break;
default:
//Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
break;
}
}
private int[] forChoices=new int[]{1,2,3};
private bool Validate(int choice)
{
if(forChoices.Contains(choice))
{
return true;
}
return false;
}
}

Can you use an array for a Switch(case)?

I've started a Uni course and I can't get me head around how to use my array for a switch case. Basically I just need the help with the switch-case, then I can get on with my work.
Heres what it looks like so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace Assignment2
{
class Program
{
public const int noOfentries = 6;
public const int address = 5;
public static string[,] addressBook = new string[noOfentries, address];//
string array for the address book
public static int deletion;
public static int choice;
public static ConsoleKeyInfo keyPressed;
public static short curItem = 0, c;
public static string[,] menuItems = new string[,]
{
{"Add Entry"},
{"Delete Entry"},
{"Print Book to Screen"},
{"Edit Contact"},
{"Exit"}
};
#region addEntry
#endregion
#region deleteEntry
#endregion
#region seeBook
#endregion
public static void fourthChoice()
{
Console.WriteLine("Would you like to edit the name or address?");
}
public static void menu()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine(menuItems[i,0].PadRight(10));
Console.Clear();
for (c = 0; c < menuItems.Length; c++)
{
if (curItem == c)
{
Console.Write(">");
Console.WriteLine(menuItems[c,0]);
Console.ForegroundColor = ConsoleColor.Green;
}
else
{
Console.WriteLine(menuItems[c,0]);
}
}
Console.WriteLine("Please select an option with the Arrow Keys");
}
}
public static void entries()
{
switch (menuItems[0,0])
{
case "Add Entry":
break;
case "Delete Entry":
break;
case "Print Book to Screen":
break;
case "Edit Contact":
break;
case "Exit":
break;
}
}
There are two aspects to a switch/case:
The value you're switching on
The cases you want to branch to
The fact that you're getting the value from an array is irrelevant. It's equivalent to:
string value = menuItems[0, 0];
switch (value)
{
}
Your cases are also constant string values, so that's fine too. (There's duplication there leading to fragile code which you may want to address, but that's a separate matter.)
... and that's fine. It's not really clear what problem you're having at the moment, although it's also unclear why you've got a rectangular array at all, given that you've only got a single "column" per row. Why not just:
public static string[] menuItems = new string[]
{
"Add Entry",
"Delete Entry",
"Print Book to Screen",
"Edit Contact",
"Exit"
};
(Leaving aside naming, accessibility, mutability etc.)
You should use an Enum for that:
private Enum myEnum { Add, Delete, Edit }
void main(myEnum state)
{
switch (state)
{
Add: //do things
break;
Edit: //do things
break;
Delete: //do things
break;
}
}

Categories