I want to write on screen result i get after completing actions at the bottom of the code. But i don't want to use Console.WriteLine() in "IF" function i want to call it as delegate carying value but it says unasigned. (site says mostly code but i dont have to say anything else so i just type something here :D )
namespace ConsoleApp5
{
class program
{
delegate int first(int a, int b);
static void Main()
{
first beta;
int result;
Console.Write("insert number A: ");
int.TryParse(Console.ReadLine(), out int a);
if (a == 0)
{
Console.WriteLine("not a number");
Environment.Exit(0);
}
Console.Write("insert number B: ");
int b = int.Parse(Console.ReadLine());
if (a == 0)
{
Console.WriteLine("not a number");
Environment.Exit(0);
}
Console.WriteLine("plus(1) or minus (0)");
int c = int.Parse(Console.ReadLine());
if (c == 1)
{
beta = plus;
result = beta(a, b);
Console.WriteLine(result);
}
else if (c == 0)
{
beta = minus;
result = beta(a, b);
Console.WriteLine(result);
}
beta(); // PROBLEM HERE, I WANT TO WRITE ANSWER FROM THIS
//instead of "Console.WriteLine(result);" inside function
}
private static int plus(int a, int b)
{
return a + b;
}
private static int minus(int a, int b)
{
return a - b;
}
}
}
Example what i mean i want to accomplish but a bit in different way.
using System;
namespace consoleApplication4
{
class Program{
Delegate void Message();
static void Main (string[] args)
{
Message mes;
if (DateTime.Now.Hour < 12)
{
mes=GoodMorning;
}
else{
mes=GoodEvening;
}
mes(); //this does what i want here but in code above something is missing
Console.ReadKey();
}
private static void GoodMorning(){
console.WriteLine("Good Morning");
}
Private static void GoodEvening(){
Console.WriteLine("Good Evening");
}}}
You already have correct code to call your delegate in both branches of if. So to get code almost working those two lines calling beta need to be moved out of both branches:
if (c == 1)
{
beta = plus;
}
else if (c == 0)
{
beta = minus;
}
result = beta(a, b);
Console.WriteLine(result);
Now the other problem is still there - your if checks have 3 outcomes (0, 1, other) but beta is only assigned in two of cases. So we need to add that "other" case too with some desired output (or simply failure), switch statement expresses it better than chained ifs:
switch (c)
{
case 1: beta = plus; break;
case 0: beta = plus; break;
default: beta = (a,b)=>""; break;
// alternatively to fail: default: return 0;
}
result = beta(a, b);
Console.WriteLine(result);
Related
I am trying to make a menu with different options on replit where the user can choose an option.
I am making the options on seperate files, so I later can call for the methods from those files instead of writing everything in the main file.
One of these menuoptions will have an option with a random generator which will generate a random string.
I created the method on another file, But when it gave me an error (7036) when i tried to call it to the main method.
I have pasted an example of the code here below, But you can also access and run the code on this link: https://replit.com/#AY2002/testc22#main.cs Which will be easier to understand. I am a begginer and, Therefore seeking a simple answer.
Thank you!
//MAIN replit FILE
using System;
using System.Collections.Generic;
namespace Namespace1 {
// This is the main file where the menu is built. the menu is working fine.
// the menu have 4 options and an exit option, which will be divided into 4 different replit files and one of them will have a method that randomly generates a string. you can see the method when you scroll down near to the bottom of the main file.
class Program {
public static void Main (string[] args)
{
string[] Menuchoises = new string [] {"Choise1","Choise2","Choise3","Choise4","Choise5"};
int x = 0;
while (true){
Console.Clear();
Console.WriteLine("welcome to menu");
Console.WriteLine();
Console.CursorVisible = false;
if(x == 0) {
Console.WriteLine(" " + Menuchoises[0] + " {");
Console.WriteLine(Menuchoises[1]);
Console.WriteLine(Menuchoises[2]);
Console.WriteLine(Menuchoises[3]);
Console.WriteLine(Menuchoises[4]);
}
else if(x == 1) {
Console.WriteLine(Menuchoises[0]);
Console.WriteLine(" " + Menuchoises[1] + " {");
Console.WriteLine(Menuchoises[2]);
Console.WriteLine(Menuchoises[3]);
Console.WriteLine(Menuchoises[4]);
}
else if(x == 2) {
Console.WriteLine(Menuchoises[0]);
Console.WriteLine(Menuchoises[1]);
Console.WriteLine(" " + Menuchoises[2] + " {");
Console.WriteLine(Menuchoises[3]);
Console.WriteLine(Menuchoises[4]);
}
else if(x == 3) {
Console.WriteLine(Menuchoises[0]);
Console.WriteLine(Menuchoises[1]);
Console.WriteLine(Menuchoises[2]);
Console.WriteLine(" " + Menuchoises[3] + " {");
Console.WriteLine(Menuchoises[4]);
}
else if(x == 4) {
Console.WriteLine(Menuchoises[0]);
Console.WriteLine(Menuchoises[1]);
Console.WriteLine(Menuchoises[2]);
Console.WriteLine(Menuchoises[3]);
Console.WriteLine("\t" + Menuchoises[4] + " {");
}
var key = Console.ReadKey();
if (key.Key == ConsoleKey.DownArrow && x != Menuchoises.Length -1) {
x++;
}
else if (key.Key == ConsoleKey.UpArrow && x>=1) {
x--;
} else if (key.Key == ConsoleKey.Enter) {
switch (x) {
case 0:
Menuchoise1();
break;
case 1:
Menuchoise2();
break;
case 2:
Menuchoise3();
break;
case 3:
Menuchoise4();
break;
case 4:
Menuchoise5();
break;
}
}
}
}
public static void Menuchoise1() {
// Class2.second is the name of the second class which will be the method that will appear when you choose the 1st option in the menu.
// The second class is in the second file which you`ll see below the main file
// The CS 7036 error seems to be appearing here
Class2.second();
Console.Clear();
Console.ReadKey();
}
public static void Menuchoise2() {
Console.Clear();
Console.ReadKey();
}
public static void Menuchoise3() {
Console.Clear();
Console.ReadKey();
}
public static void Menuchoise4() {
Console.Clear();
Console.ReadKey();
}
public static void Menuchoise5() {
Console.Clear();
Console.WriteLine("press enter to exit the menu");
Console.ReadKey();
Console.Clear();
Environment.Exit(1);
}
}
}
// SECOND replit FILE
//this is the second file where i have the random value generator.
using System;
using System.Collections.Generic;
namespace Namespace1 {
// class name of the second file
public class Class2 {
// the string[]args function that will later be put in the main file in order to use this method in the menu
public static string second(string[] Random) {
string[] RandomChoises = new string [4];
// list on options which will be randomly generated
RandomChoises[0] = "C1";
RandomChoises[1] = "C2";
RandomChoises[2] = "C3";
RandomChoises[3] = "C4";
RandomChoises[4] = "C5";
for (int i = 0; i < RandomChoises.Length; i++)
{
Console.WriteLine(RandomChoises[i]);
}
// the choises are randomly generated here
Random rnd = new Random();
int Randomanswer = rnd.Next(1,RandomChoises.Length);
Console.WriteLine("You got the answer: " + RandomChoises[Randomanswer]);
return Convert.ToString(Randomanswer);
}
}
}
As mentioned in the comments, the problem is that the second method takes a parameter, but is not called with one. Since the parameter is not used it should be removed. Cleaning up the class a bit should give you something like:
public static class RandomHelpers{
public static string GetRandomValue() {
// use collection initializer
string[] choices= new []{"C1","C2","C3","C4","C5"}
// use foreach loop
foreach(var choice in choices){
Console.WriteLine(choice );
}
// You should probably not recreate the random object for each method call
// But this should work fine for demonstration purposes
Random rnd = new Random();
// start from zero
int randomIndex = rnd.Next(0,RandomChoises.Length);
var randomValue = choices[randomIndex];
// You should probably just return the random value,
// and let the caller print it to console.
Console.WriteLine("You got the answer: " + randomValue );
// Either return the index as an int, or the value as a string
// Do not convert numbers to strings unless you are writing to the console/file
return randomValue ;
}
}
This should work better. As you get more experience you should find better ways to split functionality into reusable methods.
You have an issue with the way you are defining the array in second.cs. You either need explicitly say how many elements your array will have, like this:
string[] RandomChoice = new string[5];
Or you can leave the number out and let the compiler infer it from the number of elements you put in the {}, like this:
string[] RandomChoises = new string[] { "C1", "C2", "C3", "C4", "C5" };
You can read more details about declaring arrays in C# here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/arrays/
After you fix that see JonasH answer about the method parameters in second().
I'm an extreme beginner, only a few days into learning, so sorry if this is an obvious question.
I'm trying to use ReadLine() to get the user to enter a string (Rock, Paper or Scissors), then use an if statement to assign a variable of the same names a number 1-3 and then return to break out of the statement and then write the value in Main(). I've done the first one here b/c no point doing the rest (again) if it doesn't work for one.
The error messages from VS Code are
There is no argument given that corresponds to the required formal parameter 'choice' of 'RockPaperScissors.Method()'
and
Not all code paths return a value
What am I forgetting/misunderstanding?
using System;
class RockPaperScissors
{
static int Method()
{
string playerString = Console.ReadLine();
int rock = 1;
if (playerString == "Rock")
{
int choice = rock;
return choice;
}
}
static void Main()
{
int Move = Method();
Console.WriteLine(Move);
}
}
As it is mentioned in the error, your code handle only one use case, and it didn't return an integer for the rest of cases.
This may help:
static int Method()
{
var playerString = Console.ReadLine();
switch (playerString)
{
case "Rock":
return 1;
case "Paper":
return 2;
case "Scissors":
return 3;
default:
// when the input data is not one of the previous strings
// it throws an exception so it should be catched and handled
throw new Exception("Not valid input");
}
}
Or, making the code easier to read by using an enum:
public enum HandSign
{
Rock, // rock beats scissors
Paper, // paper beats rock
Scissors, // scissors beats paper
}
Which allows this:
public static HandSign GetUserChoice()
{
HandSign result = default;
bool isCorrectEntry = false;
while (!isCorrectEntry)
{
Console.Write(#"Enter choice (Rock/Paper/Scissors): ");
var enteredText = Console.ReadLine();
isCorrectEntry = Enum.TryParse<HandSign>(enteredText, ignoreCase:true, out result);
}
return result;
}
Notice that it will prompt you over and over again until you spell scissors correctly. It also ignores the case of the entered text.
static int Method()
{
string playerString = Console.ReadLine();
int rock = 1;
if (playerString == "Rock")
{
int choice = rock;
return choice;
}
return rock;
}
I'm currently in programming 101 and I've been stuck for a long time with an issue.
My assignment wants me to create a class with a bunch of methods to run with a switch case( as a menu).
If I press 1 (add passenger), it does what it's supposed to do the first time, but the second time, it just restarts the array.
I can't seem to save my answer to the array and then move on to the next spot in the array.
Would someone please explain how I'm supposed to "call" the array and save in it outside my for-loop in method add_pass?
using System;
namespace bussen
{
class buss
{
public int[] passagerare;
public int numbof_passagerare;
public void Run()
{
int nmr = 0;
do
{
Console.WriteLine("options:");
Console.WriteLine("1 add passenger");
Console.WriteLine("2 print out all passengers");
Console.WriteLine("3 calc average age");
Console.WriteLine("0 close program");
nmr = int.Parse(Console.ReadLine());
switch (nmr)
{
case 1:add_pass();
break;
case 2:all_pass();
break;
case 3:
break;
case 0:
break;
}
} while (nmr != 0);
}
public void add_pass()
{
if (passagerare.Length < 5)
{
for (int i = 0; i < passagerare.Length; i++)
{
Console.WriteLine("type age of passenger");
int numbof_passenger = int.Parse(Console.ReadLine());
passagerare[i] = numbof_passenger;
break;
}
}
else if(passagerare.Length >= 5)
{
Console.WriteLine("buss is full");
}
}
public void all_pass()
{
foreach(int index in passagerare)
{
Console.WriteLine(index);
}
}
}
class Program
{
static void Main(string[] args)
{
var minbuss = new buss();
minbuss.Run();
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
It's starting over because you're telling it to start over. The for loop starts at 0 every time.
for (int i = 0; i < passagerare.Length; i++)
{
Console.WriteLine("type age of passenger");
int numbof_passenger = int.Parse(Console.ReadLine());
passagerare[i] = numbof_passenger;
break;
}
You need to find the length of the array and append the new entry. Try using a List instead of any array.
The issue was within the add_pass method, where i used a for - loop to add passengers. each time i pressed number 1 in the menu to call the method , the loop restarted the array wich i was saving the integers to.To get this right i just called the method without a loop like shown below. Thanks everybody for your help!
public void add_pass()
{
if (numbof_passagerare < 5)
{
Console.WriteLine("how old is the passenger");
int age = int.Parse(Console.ReadLine());
passagerare[numbof_passagerare++] = age;
}
else if(numbof_passagerare == 5)
{
Console.WriteLine("buss is full!");
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ArithmaticOperation
{
class Program
{
delegate double ArithmaticDelegate(double x, double y);
static void Menu()
{
Console.WriteLine("Select an arithmatic operation");
Console.WriteLine("1)Addition");
Console.WriteLine("2)Subtraction");
Console.WriteLine("3)Multiplication");
Console.WriteLine("4)Division");
Console.WriteLine("5)Remainder");
Console.WriteLine("6)Quit");
}
static double Add(double a, double b)
{
return a + b;
}
static double Subtract(double a, double b)
{
return a - b;
}
static double Multiply(double a, double b)
{
return a * b;
}
static double Divide(double a, double b)
{
return a / b;
}
static double Modulus(double a, double b)
{
return a % b;
}
static void Main(string[] args)
{
int operation;
ArithmaticDelegate arithmatic;
double x, y;
do
{
Console.WriteLine("Enter two numbers seperated by Enter");
x = double.Parse(Console.ReadLine());
y = double.Parse(Console.ReadLine());
Console.Clear();
Menu();
operation = int.Parse(Console.ReadLine());
switch (operation)
{
//Addition
case 1:
arithmatic = new ArithmaticDelegate(Add);
break;
//Subtraction
case 2:
arithmatic = new ArithmaticDelegate(Subtract);
break;
//Multiplication
case 3:
arithmatic = new ArithmaticDelegate(Multiply);
break;
//Division
case 4:
arithmatic = new ArithmaticDelegate(Divide);
break;
//Remainder
case 5:
arithmatic = new ArithmaticDelegate(Modulus);
break;
default:
Console.WriteLine("Exiting program");
break;
}
Console.Clear();
Console.WriteLine(arithmatic(x, y));
Console.WriteLine("Press any key to continue");
Console.ReadKey(true);
Console.Clear();
} while (operation != 6);
}
}
}
I am trying to write a simple calculator using delegates. The code below would give an error at the line 81 "Console.WriteLine(arithmatic(x,y));" reporting that the variable arithmatic is unassigned local variable. I believe the cause has something to do with the variable scope in the do-while and the switch body, however the variable is declared outside the do-while so its scope should span the entire main method, and anything assigned to it from within the do-while and switch statement should remain in effect after its outside. Yet the compiler still report its uninitialized/unassigned
You are getting error message because arithmatic is not initialized in all the cases of switch statement (meaning not assigned in all execution paths).
To fix this issue:
either have some dummy method and assign that dummy method in default
static double DummyMethod(double a, double b)
{
return 6; // or any number other than 1 through 5
}
and in default case, arithmatic = DummyMethod;
(or) initialze as below:
So, to fix the error: please modify your programs to initialize arithematic as below:
ArithmaticDelegate arithmatic = null;
and then surround your arithematic call with if as below:
if (arithmatic != null)
{
Console.WriteLine(arithmatic(x, y));
}
or return in default case to skip the execution path when control enters into default case.
I am facing a problem in creating a console application in Visual Studio c# 2005
I created the following program in which a method (to sum 2 predefined values) is called in the program
here is the code of it
class program
{
static void Main()
{
program a;
a = new program();
Console.WriteLine(a.am1(1,2));
Console.ReadLine();
}
int sum;
public int am1(int num1, int num2)
{
sum = num1 + num2;
return sum;
}
}
Now here is the main problem I am facing, well in this program two integers (num1 and num2) are predefined, I wanted those 2 numbers to be taken from user, means user input the two numbers and then the same program goes on like above. How it should be done?
P.S remember everything should be done in methods
i hope i got your requirements ... if not, please elaborate!
public sealed class Program
{
private readonly int _number1;
private readonly int _number2;
public Program(int number1, int number2)
{
this._number1 = number1;
this._number2 = number2;
}
public int Sum()
{
return this._number1 + this._number2;
}
public static void Main(string[] args)
{
// this one here is really brutal, but you can adapt it
int number1 = int.Parse(args[0]);
int number2 = int.Parse(args[1]);
Program program = new Program(number1, number2);
int sum = program.Sum();
Console.WriteLine(sum);
Console.ReadLine();
}
}
sry, this is not my main coding style ... pfuh ... really ugly!
edit:
don't give blind trust in int.Parse(). the params are coming from the user, you better double check them!
you better triple check them, as you are doing a sum ... thankfully c# compiles with unchecked - this code may fail with an OverflowException if compiled in vb - remember ranges of int
why do you want to do a simple addition in an extra class?
you should elaborate your style (regarding your comment): separate ui-code from business-layer code!
you do not need to create an instance variable for each task - you can do that with scope variables too...!
...
Use console application command line arguments. If it suites you. Below is an example from MSDN.
public class Functions
{
public static long Factorial(int n)
{
// Test for invalid input
if ((n < 0) || (n > 20))
{
return -1;
}
// Calculate the factorial iteratively rather than recursively:
long tempResult = 1;
for (int i = 1; i <= n; i++)
{
tempResult *= i;
}
return tempResult;
}
}
class MainClass
{
static int Main(string[] args)
{
// Test if input arguments were supplied:
if (args.Length == 0)
{
System.Console.WriteLine("Please enter a numeric argument.");
System.Console.WriteLine("Usage: Factorial <num>");
return 1;
}
// Try to convert the input arguments to numbers. This will throw
// an exception if the argument is not a number.
// num = int.Parse(args[0]);
int num;
bool test = int.TryParse(args[0], out num);
if (test == false)
{
System.Console.WriteLine("Please enter a numeric argument.");
System.Console.WriteLine("Usage: Factorial <num>");
return 1;
}
// Calculate factorial.
long result = Functions.Factorial(num);
// Print result.
if (result == -1)
System.Console.WriteLine("Input must be >= 0 and <= 20.");
else
System.Console.WriteLine("The Factorial of {0} is {1}.", num, result);
return 0;
}
}
// If 3 is entered on command line, the
// output reads: The factorial of 3 is 6.