First time using a separate class (.cs) file for a method - c#

Sorry for posting this wall of garbage code :( I didn't want to leave anything out! Im still new and got a little ahead of myself. I wanted to put the "switch case" in a new class so I could reference it faster while also learning to make a new class file. Unfortunately I ran into one bug after another and I couldn't figure out why. The main issue i had is that when I call the case number in the main method, it only returns the string.
Ex. I want the output to be:
"Well [user created name], are you ready to begin your journey to the edge of the world?"
It seems there is an issue with the two classes communicating with eachother.
I have made it worse throwing "public static" at everything to try to make it work. I would really appreciate the help.
using System;
using Test;
public class Scripts
{
public Program p { get; set; }
public void Script(int s)
{
switch (s)
{
case 1:
p.output = "Quest to the edge of the world!";
p.WriteLine();
break;
case 2:
p.output = "Hello! I am your instructor. What is your name apprentice?";
p.WriteLine();
break;
case :
p.output = p.name + " you say? My, what a strange name.";
p.WriteLine();
break;
case 4:
p.output = "Well " + p.name + ", are you ready to begin your journey to the edge of the world?";
p.WriteLine();
break;
case 5:
p.output = " (y)Yes on (n)No";
p.WriteLine();
break;
case 6:
p.output = "OK! Before we go lets go over our gear. What should we prioritize? (1)Magic, (2)Melee, or (3)Ranged?";
p.WriteLine();
break;
case 7:
p.output = "Well I'll just come back tomorrow then.";
p.WriteLine();
break;
case 8:
p.output = "I'm sorry... that's not an option.";
p.WriteLine();
break;
case 9:
p.output = "I'm pretty good at " + p.combatStyle + " combat myself, I'll be sure to teach you everything I know.";
p.WriteLine();
break;
case 10:
p.output = "OK! Let's hit the road and make camp at sundown.";
p.WriteLine();
break;
case 11:
p.output = "Chapter " + p.chapter;
p.WriteLine();
break;
case 12:
p.output = p.name + ", wake up!Were under attack by a couple of goblins!";
p.WriteLine();
break;
case 13:
p.output = "I guess this is the perfect chance to teach you a new" + p.form + "called";
p.WriteLine();
break;
case 14:
p.output = "It makes quick work of their health, but your" + p.energyBar + " will go down just as fast so use it wisely!";
p.WriteLine();
break;
case 15:
p.output = "I'll take care of the one on the right, you engage the one on the left.";
p.WriteLine();
break;
case 16:
p.output = "Press (f) to enter combat. Then press (1) to make an attack";
p.WriteLine();
break;
default:
break;
}
}
}
using System;
using System.Threading;
namespace Test
{
public class Program
{
public Scripts s { get; set; }
// Class Global Variables
public static string input;
public static string output;
public static string name = "bob";
private static string yes = "y";
private static string no = "n";
private static string option1 = "1";
private static string option2 = "2";
private static string option3 = "3";
private static string pathA;
private static string pathB;
private static string pathC;
public static string combatStyle;
private static string weapon;
public static string chapter = "Zero";
public static string form;
public static string energyBar;
private static string healthBar;
Program p = new Program();
public static string[] numbers = new string[] { "One","Two", "Three", "Four", "Five" };
private static int mp = 100;
private static int stamina = 100;
private static int script;
//ReadLine & WriteLine Methods
private static void ReadLine()
{
Console.SetCursorPosition((Console.WindowWidth - 110) / 2, Console.CursorTop);
input = Console.ReadLine();
}
public static void WriteLine()
{
Thread.Sleep(2000);
Console.SetCursorPosition((Console.WindowWidth - output.Length) / 2, Console.CursorTop);
Console.WriteLine(output);
}
//Next Chapter Screen
private static void nextChapter()
{
Thread.Sleep(3000);
Console.Clear();
Thread.Sleep(1500);
output = "\r\n\r\n\r\n\r\n";
WriteLine();
//output = script[12] + chapter;
WriteLine();
Console.Beep();
Thread.Sleep(1500);
Console.Clear();
}
//Yes or No Decision
private static void YesNo()
{
while (input != yes && input != no)
{
ReadLine();
if (input == yes)
{
output = pathA;
WriteLine();
}
else if (input == no)
{
output = pathB;
WriteLine();
}
else
{
//output = script[8];
WriteLine();
}
}
input = "";
}
//Multiple Choice Decision
private static void Choice()
{
while (input != option1 && input != option2 && input != option3)
{
ReadLine();
if (input == option1)
{
output = pathA;
WriteLine();
}
else if (input == option2)
{
output = pathB;
WriteLine();
}
else if (input == option3)
{
output = pathC;
WriteLine();
}
else
{
//output = //script[8];
//WriteLine();
}
}
input = "";
}
//Combat Loop
private static void combatLoop()
{
if (input == "f")
{
}
else
{
//output = script[8];
WriteLine();
combatLoop();
}
}
//Main Method
static void Main()
{
//Chapter Zero "Intro"
Scripts s = new Scripts();
s.Script(1);
s.Script(2);
ReadLine();
name = input;
Console.WriteLine(input);
Console.WriteLine(name);
s.Script(3);
//Chapter One "Combat"
//Chapter Two "Trading"
//Chapter Three "Dungeon"
//Chapter Four "Sailing"
//Chapter Five "The Edge"
// Keep the console open in debug mode.
Console.WriteLine("Press any key to quit game.");
Console.ReadKey();
}
}
}

Looks like your class is in a separate namespace, and the existing namespace for program is not using a using statement for including your separate class.

If you're using static methods / variables, you shouldn't use the object, you should use the class itself:
Program.output = "bla";
Program.WriteLine();
instead of
p.output = "bla";
p.WriteLine();
As your field p isn't even initalized, your current code shouldn't compile. If you want to use the object, you should pass it like that:
public void Script (int s, Program p)
Then you could also make your methods non-static.
Also I'm wondering why you're setting your cursor position to half the length of the text from the right - why not the full offset?
Furthermore you're saying that
The main issue i had is that when I call the case number in the main method, it only returns the string.
What do you mean by returning the string? Your Script method doesn't even have a return type (except for void).

Related

First console application returning with unexpected output

When I run this console app, everything works fine but except for my UserAnswer() result. It keeps returning a value of '0' for both num1 & num2. This doesn't make sense to me because I don't receive any errors for declaring a new value for num1 & num2 in Input1() & Input2() methods. It compiles and runs fine but why is it not picking up the new values of these variables?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalculatorApp
{
public class Program
{
float Number;
float num2;
float num1;
public static void Main(string[] args)
{
// Display title as the C# console calculator app.
Console.WriteLine("Console Calculator in C#\r");
Console.WriteLine("------------------------\n");
//Console.ReadKey();
// execute program functions
new Program().Input1();
new Program().Input2();
new Program().UserOption();
new Program().UserAnswer();
new Program().PromptUserExit();
}
// Ask the user to type the first number.
//Console.WriteLine("Type a number, and then press Enter");
public float Input1() {
Console.WriteLine("Type a number, and then press Enter");
bool Valid = false;
while (Valid == false)
{
string Input = Console.ReadLine();
if (!float.TryParse(Input, out Number))
{
Console.WriteLine("Not an integer, please try again.");
}
else
{
Valid = true;
num1 = (float)Convert.ToDecimal(Input);
}
} return num1;
}
public float Input2() {
// Ask the user to type the second number.
Console.WriteLine("Type another number, and then press Enter");
bool Valid2 = false;
while (Valid2 == false)
{
string Input2 = Console.ReadLine();
if (!float.TryParse(Input2, out Number))
{
Console.WriteLine("Not an integer, please try again.");
}
else
{
Valid2 = true;
num2 = (float)Convert.ToDecimal(Input2);
}
} return num2;
}
public void UserOption() {
// Ask the user to choose an option.
Console.WriteLine("Choose an option from the following list:");
Console.WriteLine("\ta - Add");
Console.WriteLine("\ts - Subtract");
Console.WriteLine("\tm - Multiply");
Console.WriteLine("\td - Divide");
Console.Write("Your option? ");
}
public void UserAnswer() {
bool isOperatorValid;
do
{
isOperatorValid = true;
switch (Console.ReadLine())
{
case "a":
Console.WriteLine($"Your result: {num1} + {num2} = " + (num1 + num2));
break;
case "s":
Console.WriteLine($"Your result: {num1} - {num2} = " + (num1 - num2));
break;
case "m":
Console.WriteLine($"Your result: {num1} * {num2} = " + (num1 * num2));
break;
case "d":
Console.WriteLine($"Your result: {num1} / {num2} = " + (num1 / num2));
break;
default:
Console.WriteLine("Invalid input please try again");
isOperatorValid = false;
break;
}
} while (!isOperatorValid);
}
public void PromptUserExit() {
// Wait for the user to respond before closing.
Console.Write("Press any key to close the Calculator console app...");
Console.ReadKey();
}
}
}
This is your problem:
new Program()
You are creating a new instance of the Program class every time you call a method. Each time, the variables are initialized with the default value of 0.
You need to initialize the class once, then use the same class:
var program = new Program();
program.Input1();
program.Input2();
program.UserOption();
program.UserAnswer();
program.PromptUserExit();
Or you could just make all of your methods and variables static so that you can call them directly without initializing a new object. In bigger programs, you would want to be careful with declaring things static (there is a time and place, but it's not "always"). But in a small program like this, it's fine.

Allowing user to choose to display entire number in calculator or only 2 decimals

I'm making a basic calculator and I'm wondering how I would go on to make the user choose if he/she wants to display the full result or only the result with 2 decimals. For example, if user puts in first number 4.213 and second number 4.6321, method "+" then the console asks "Do you wish to display the entire result or round it to 2 decimals" at which the user can type in "Yes" or "No".
I'm not looking for the program to round up the decimals, just display 2 decimals or the entire number.
I'm guessing if and else statement would be the way to go here.
Code:
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
private static int runda;
static void Main(string[] args)
{
List<double> Numbers = new List<double>();
string Method = "";
while (true)
{
loop:
try
{
Numbers.Add(ConvStr(TakeUserInput("First Number:")));
}
catch
{
Console.Clear();
Console.WriteLine("Error, try again.");
Console.ReadLine();
goto loop;
}
Console.Clear();
looop:
try
{
Numbers.Add(ConvStr(TakeUserInput("Second Number:")));
}
catch
{
Console.Clear();
Console.WriteLine("Error, try again.");
Console.ReadLine();
goto looop;
}
Console.Clear();
do
{
Method = TakeUserInput("Choose method: ");
Console.Clear();
Console.WriteLine("Error (Endast Addition (+) Subtraktion (-) Multiplikation (*) samt division (/)");
}
while (!CheckMethod(Method));
Console.Clear();
**HERE IS WHERE I WOULD LIKE USER TO CHOOSE IF DISPLAY ENTIRE NUMBER OR ONLY 2 DECIMALS**
Console.WriteLine("Result:");
Console.WriteLine(Calc(Numbers, Method));
Console.WriteLine("If you wish to keep using this calculator press Enter.");
Console.ReadLine();
Numbers.Clear();
}
}
private static string TakeUserInput(string DisplayText)
{
Console.Write(DisplayText);
return Console.ReadLine();
}
private static bool CheckMethod(string method)
{
switch(method)
{
case "+":
break;
case "-":
break;
case "*":
break;
case "/":
break;
default:
return false;
}
return true;
}
private static double Calc(List<double> input, string method)
{
double Answer = 0;
switch (method)
{
case "+":
Answer = input[0] + input[1];
break;
case "-":
Answer = input[0] - input[1];
break;
case "*":
Answer = input[0] * input[1];
break;
case "/":
Answer = input[0] / input[1];
break;
}
return Answer;
}
private static double ConvStr(string input)
{
return Convert.ToDouble(input = input.Replace(".", ","));
}
}
}
Might be wrong but couldn’t you
1). Turn the integer(result) into a string
2). Use the .indexOf(“”) function on the string to get the location of the period
3). check the index+3 to be in range of the result in order to not give any errors (3 to skip the period as well)
4). Use the .remove(index) function to remove all other numbers at the new index
5). Use Convert.toInt32(string) to get its value back
Also there is a “Data.” something function which enables you to calculate the result of a string representation of the expression if that is of any help

how will I access the methods into my Switch statement? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
how do I access the methods??
how do I access the methods??
and use them in Switch statement?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace practise_Delegates_MenuDriven
{
class Program
{
delegate int Converter(int value);
static int ToCel(int fah)
{
return fah;
}
static int ToFah(int celsius)
{
return celsius;
}
static int ToKel(int celsius2)
{
return celsius2;
}
static int ToRank(int celsius3)
{
return celsius3;
}
static void DisplayMenu()
{
Console.WriteLine("Celsius Converter");
Console.WriteLine("=================");
Console.WriteLine("C - Celsius to Fahrenheit");
Console.WriteLine("F - Fahrenheit to Celsius");
Console.WriteLine("K - Celsius to Kelvin");
Console.WriteLine("R - Celsius to Rankine");
Console.WriteLine("X - Exit");
}
static char GetMenuOption(char letter)
{
Console.WriteLine("Please enter C, F, K, R, X: ");
letter = Convert.ToChar(Console.ReadLine());
return letter;
}
static int GetValue(int value)
{
Console.WriteLine("Please enter the value to convert: ");
value = Convert.ToInt32(Console.ReadLine());
return value;
}
static void PrintResult(int fromValue,int result,string fromstring,string toString)
{
Console.WriteLine(fromValue + " " + fromstring + " is " + result + " " + toString);
}
static void Main(string[] args)
{
Converter process = ToCel;
Converter process1 = ToCel;
Converter process2 = ToKel;
Converter process3 = ToKel;
***switch statement? while loop?***
}
}
}
You don't need arguments in GetMenuOption() and GetValue() methods. And here is loop (it is needed if you want to process more than one temperature) with switch:
while (true)
{
DisplayMenu();
var letter = GetMenuOption();
var fromString = String.Empty;
var toString = String.Empty;
if (letter == 'X')
{
break;
}
var fromValue = GetValue();
var result = 0;
switch (letter)
{
case 'C':
fromString = "F";
toString = "C";
result = process(fromValue);
break;
case 'F':
fromString = "C";
toString = "F";
result = process1(fromValue);
break;
case 'K':
fromString = "C";
toString = "K";
result = process2(fromValue);
break;
case 'R':
fromString = "C";
toString = "R";
result = process3(fromValue);
break;
}
PrintResult(fromValue, result, fromString, toString);
}
switch (charValue) {
case 'C':
ToCel(int val);
break;
case 'F':
ToFah(int val);
break;
//rest of the case
default:
Console.WriteLine("invalid value");
break;
}
You need to pass the character input into the switch statement, then you can decide what to do for each different case.
also, why are you passing a char and an int into GetMenuOption and GetValue?
it should be like this, unless you have a good reason
static char GetMenuOption()
{
Console.WriteLine("Please enter C, F, K, R, X: ");
char letter = Convert.ToChar(Console.ReadLine());
return letter;
}
static int GetValue()
{
Console.WriteLine("Please enter the value to convert: ");
int value = Convert.ToInt32(Console.ReadLine());
return value;
}

not recognizing a declared variables in c#.net

The last but 3rd line of code is not recognizing variables that I have declared and filled with strings.
static void Main(string[] args)
{
string inputNumber = "1979";
string input1 = inputNumber.Substring(0, 1);
string input2 = inputNumber.Substring(1, 1);
string input3 = inputNumber.Substring(2, 1);
string input4 = inputNumber.Substring(3, 1);
int intInput1;
int intInput2;
int intInput3;
int intInput4;
intInput1 = Convert.ToInt32(input1);
intInput2 = Convert.ToInt32(input2);
intInput3 = Convert.ToInt32(input3);
intInput4 = Convert.ToInt32(input4);
string stringOutput1;
string stringOutput2;
string stringOutput3;
string stringOutput4;
// 1000 Input.
switch (intInput1)
{
case 1:
stringOutput1 = "M";
break;
default:
break;
}
//100 Input
switch (intInput2)
{
case 9:
stringOutput2 = "CM";
break;
default:
break;
}
//10 Input
switch (intInput3)
{
case 7:
stringOutput3 = "LXX";
break;
default:
break;
}
//1 Input
switch (intInput4)
{
case 9:
stringOutput4 = "IX";
break;
default:
break;
}
//Use of unassigned local variable error is showing for 'stringOutput1', 'stringOutput2', 'stringOutput3' and 'stringOutput4'
Console.WriteLine("{0} is {1}{2}{3}{4} in Roman Numerals",inputNumber, stringOutput1, stringOutput2, stringOutput3, stringOutput4);
Console.CursorVisible = false;
Console.ReadKey();
}
P.S. I know that the variables are being filled by commenting out
Console.WriteLine("{0} is {1}{2}{3}{4} in Roman Numerals",inputNumber, stringOutput1, stringOutput2, stringOutput3, stringOutput4);
and using break point and stepping over the code.
This is because your variables might not have been assigned anything yet. Variables must be guaranteed to have been assigned something before they can be used. As a simple fix, you can use declarations like this:
string stringOutput1 = "";
Try assigning nulls to the declarations
string stringOutput1 = null;
string stringOutput2 = null;
string stringOutput3 = null;
string stringOutput4 = null;
You have to initialize your variables, do it like this.
string stringOutput1 , stringOutput1, stringOutput3, stringOutput4 = string.Empty;
and you can also assign default values per variable.
string stringOutput1 = "foo1", stringOutput1 = "foo2"
, stringOutput3= "foo3", stringOutput4 = "foo4";

Where to put my functions so that it can be called from my switch statement?

I am very new in C# programming and I have a problem. I dont know where to put my functions and how to declare them so that I can call them from my switch statement. And will I be able to use my numberarr and wordarr array in my functions or do I also need to create a separate function for it Here is my code:
class Program
{
enum Menu
{
Numbers = 1,
Words = 2,
Exit = 3,
}
static void Main(string[] args)
{
bool isValid;
do
{
isValid = true;
Menu menu = 0;
int number;
string word;
Console.WriteLine("Choose an option from the menu: ");
Console.WriteLine("1. Numbers ");
Console.WriteLine("2. Words ");
Console.WriteLine("3. Exit ");
switch (menu)
{
case Menu.Numbers:
List<int> numberarr = new List<int>();
Console.WriteLine("Please input as many numbers as you like or type exit");
number = int.Parse(Console.ReadLine());
numberarr.Add(number);
break;
case Menu.Words:
List<string> wordarr = new List<string>();
Console.WriteLine("Please input as many numbers as you like");
word = Console.ReadLine();
wordarr.Add(word);
break;
case Menu.Exit:
break;
default:
Console.WriteLine("You have made an invalid selection, try again");
isValid = false;
break;
}
} while (isValid);
}
}
class Choice
{
static void Numbers(int sum, int count, int average, int max, int min)
{
}
static void Words(string[] args)
{
}
static void Exit()
{
}
}
You can't use the methods defined in the Choice class in Main because you haven't declared them with the public identifier. In C# class properties default to being private so unless you explicitly declare them as public only the class itself will know of their existence.
So basically just change all of declarations in Choice from static void MethodName to public static void MethodName and then you will be able to call them in main from the Choice class like;
Choice.Exit();
EDIT: You'll also need to make some changes to make the switch statement work. As pointed out in the comments there is no way for menu to have a value other than 0. I suggest you use something more like the following;
isValid = true;
int menu = 0;
int number;
string word;
Console.WriteLine("What type do you want to use?");
Console.WriteLine("Press 1 for numbers, 2 for words, or 3 exit.");
string input = Console.ReadLine(); // we must read the users input
if (!int.TryParse(input, out menu))
{
// the user didn't enter a number make them try again
// note you might want to use a loop here to ensure the program does not
// proceed until the user has entered "1", "2", or "3"
}
switch (menu)
If I am understanding your question, just place your functions within your class. I've adjusted your code accordingly. You may also have problems with your word/num classes. You normally have to instantiate them but with something like Choice myChoice = new Choice();
Class Program
{
enum Menu
{
Numbers = 1,
Words = 2,
Exit = 3,
}
static void Main(string[] args)
{
bool isValid;
do
{
isValid = true;
Menu menu = 0;
int number;
string word;
Console.WriteLine("Choose an option from the menu: ");
Console.WriteLine("1. Numbers ");
Console.WriteLine("2. Words ");
Console.WriteLine("3. Exit ");
switch (menu)
{
case Menu.Numbers:
List<int> numberarr = new List<int>();
Console.WriteLine("Please input as many numbers as you like or type exit");
number = int.Parse(Console.ReadLine());
numberarr.Add(number);
int retInt = functionGetInt(number)
break;
case Menu.Words:
List<string> wordarr = new List<string>();
Console.WriteLine("Please input as many numbers as you like");
word = Console.ReadLine();
wordarr.Add(word);
string retString = functionGetString(word);
break;
case Menu.Exit:
break;
default:
Console.WriteLine("You have made an invalid selection, try again");
isValid = false;
break;
}
} while (isValid);
private string functionGetString(string pParmString)
{
//code
return "string";
}
private int functionGetInt(int pParmInt)
{
//code
return 0;
}
}
}
EDIT:
For the code you presented here this would be one possibility.I removed the enum,i normally try to deal with the code presented but yes it was not necessary:
class Program
{
//enum Menu
//{
// Numbers = 1,
// Words = 2,
// Exit = 3,
//}
static void Main(string[] args)
{
bool isValid;
do
{
isValid = true;
int menu = 0;
int[] number;
string word;
Console.WriteLine("Choose an option from the menu: ");
Console.WriteLine("1. Numbers ");
Console.WriteLine("2. Words ");
Console.WriteLine("3. Exit ");
string s = Console.ReadLine();
while (!Regex.IsMatch(s, "^[1-3]{1}$"))
{
Console.WriteLine("Please enter a valid choice(1 to 3)");
s = Console.ReadLine();
}
menu = Convert.ToInt32(s);
switch (menu)
{
case 1:
List<int> numberarr = new List<int>();
Console.WriteLine("Please input as many numbers as you like separeted by space or comma,or type exit");
string numbers = Console.ReadLine();
if (numbers == "exit")
Choice.Exit();
else
{
number = numbers.Split(new char[] { ',', ' ' }).Select(x => int.Parse(x)).ToArray();
numberarr.AddRange(number);
Choice.Numbers(numberarr.Sum(), numberarr.Count, numberarr.Average(), numberarr.Max(), numberarr.Min());
}
break;
case 2:
List<string> wordarr = new List<string>();
Console.WriteLine("Please input as many numbers as you like separeted by space or comma");
word = Console.ReadLine();
wordarr.AddRange(word.Split(new char[] { ',', ' ' }));
Choice.Words(wordarr);
break;
case 3:
Choice.Exit();
break;
default:
Console.WriteLine("You have made an invalid selection, try again");
isValid = false;
break;
}
} while (isValid);
Console.ReadKey();
}
}
class Choice
{
public static void Numbers(int sum, int count, double average, int max, int min)
{
int a = sum;
int b = count;
double c = average;
int d = max;
int e = min;
//just as example.
}
public static void Words(List<string> args)
{
//do whatever you need here
}
public static void Exit()
{
Environment.Exit(0);
}
}

Categories

Resources