I'm learning C# by myself by book and would appreciate some help. I want to create a simple console program to allow the user to enter a number to be doubled. It says that the variable result in the Main method is unassigned, however, what am I doing wrong?
using System;
class Program
{
private static void Double(ref int num, ref int result)
{
result = num * 2;
}
private static int readNumber(string question)
{
Console.Write(question);
string ans = Console.ReadLine();
int number = int.Parse(ans);
return number;
}
public static void Main()
{
int num, result;
num = readNumber("Enter an integer to be doubled: ");
Double(ref num, ref result);
Console.WriteLine("The double of {0} is {1}", num, result);
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
}
}
The compiler is yelling at you because it wants to force you to initialize the variables before passing them to the method call.
Meaning:
int num, result;
Should be:
int num = 0;
int result = 0;
There may be a better way of doing what you're trying to do, without any ref parameters at all, by simply using the return value of the method:
private static int Double(int num)
{
return num * 2;
}
And consume it like this:
public static void Main()
{
int num = readNumber("Enter an integer to be doubled: ");
int result = Double(num);
Console.WriteLine("The double of {0} is {1}", num, result);
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
}
This may even (IMO) enhance the readability of your code and convey your intentions better.
´Why don´t you simply change the methods signatur to return a double instead of using a ref?
private static double Double(int num)
{
return num * 2;
}
Now you can simply call result = Double(num).
Related
I need to print mathematical table without using any loop (for, while, do while, etc.). Can anyone help me out, the easiest example I could find was writing console.writeline 10times for each line.
This is my code!
using System;
using System.Linq;
class Question4
{
int product, i=1;
public static void Main(string[] args)
{
int num;
Console.Write("Enter the Number to Print its Multiplication Table: ");
num = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nMultiplication Table For {0}: ",num);
TableFunctionName (num);
}
public void TableFunctionName(int n)
{
if(i<=10)
{
table=n*i;
Console.WriteLine("{0} x {1} = {2}",n,i,table);
i++;
}
return;
}
}
Using recursion
static void Multiply(int a, int b) {
if (a > 1)
Multiply(a - 1, b);
Console.WriteLine($"{a} * { b} = {a * b}");
}
static void Main(string[] args) {
Multiply(10, 5);
}
}
You could use recursion
public static void Main()
{
Console.Write("Enter the Number to Print its Multiplication Table: ");
var input = Console.ReadLine();
var number = Convert.ToInt32(input);
CalculateAndPrint(number, 1);
}
static void CalculateAndPrint(int number, int factor)
{
if (factor > 9) return;
Console.WriteLine("{0} x {1} = {2}", number, factor, number * factor);
CalculateAndPrint(number, ++factor);
}
I'm a new to C#, please give me some advice on my program. How to pass a value from a method to another method? I am trying to do a calculation by using the value n from part_number in another method.
class Program
{
static void Main(string[] args)
{
int n;
part_number(out n);
Athlete myobj = new Athlete();
int n1 = 0;
for (n1 = 0; n1 < n; ++n1)
{
Write("Enter your participant name >> ");
myobj.participant_Name = ReadLine();
WriteLine("Event codes are:");
WriteLine("T Tennis");
WriteLine("B Badminton");
WriteLine("S Swimming");
WriteLine("R Running");
WriteLine("O Other");
Write("Enter event code>> ");
myobj.event_Code0 = ReadLine();
}
double totalCost;
const double cost = 30.00;
totalCost = cost * n1;
WriteLine("The total cost is {0}", totalCost);
static void part_number(out int n)
{
n = 0;
WriteLine("Enter the number the participant this year>> ");
n = System.Convert.ToInt32(ReadLine());
while (n >= 40)
{
WriteLine("Please enter number between 0 to 40");
n = System.Convert.ToInt32(ReadLine());
}
}
}
How to pass the value of n from part_number method and another method? I need to the use that value to do a calculation in another method. Should I build a class for it?
Thank you!
You would simply add an argument to the method such as:
void MyOtherMethod(int number)
{
// do something with number
}
If you wanted, you could pass multiple things by commad delimiting them:
void MyOtherMethod(int number, string name)
{
}
You can also have a method returning a value:
int MyReturningMethod(int number)
{
return number + 2;
}
The possibilities are endless.
You will have to call your other method and pass it in.
public static Main(string[] args)
{
PartNumer(out var partNumber);
OtherMethod(partNumber);
}
static void PartNumber(out int pn)
{
pn =1;
}
static void OtherMehtod(int partNumber)
{
Console.WriteLine($"Your part number is {partNumber}");
}
I am making a slot machine, and I want the var 'bet' in betValidation() to be used in the result() function. My goal is if two of the random number generated in firstRandomNumberGenerator() are the same, the bet that the player bets will be tripled and will be added back to his current amount of chips. ): But in order to do that, I'll need to get bet (a local variable) and place it in result() but I don't know how.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace randomProjectTAKE3
{
class Program
{
static void Main()
{
float playerChips = 1000;
Console.Write("Player's Chips: ");
Console.WriteLine(playerChips);
Console.Write("1. Play Slot ");
Console.WriteLine("2. Exit");
choice();
result();
Console.ReadKey();
}
static void Update()
{
}
static void choice()
{
float choice = float.Parse(Console.ReadLine());
if (choice == 1)
{
firstRandomNumberGenerator();
}
else if (choice == 2)
{
return;
}
}
static void betValidation()
{
float playerChips = 1000;
float currentPlayerChips;
Console.WriteLine("Enter your bet: ");
**var bet = float.Parse(Console.ReadLine());**
if ((bet <= 0) || (bet > playerChips))
{
Console.WriteLine("You did not enter a valid bet.\n");
Main();
}
}
static void firstRandomNumberGenerator()
{
betValidation();
Random r = new Random();
int firstNumber = r.Next(2, 8);
int secondNumber = r.Next(2, 8);
int thirdNumber = r.Next(2, 8);
Console.Write(firstNumber);
Console.Write(secondNumber);
Console.Write(thirdNumber);
Console.Write("\n");
}
**static void result()**
{
}
}
}
There is a few ways to make this happen, one way is to move the bet into the scope of the program as a field (the name _currentBet would be useful), rather than declared in the function so it can be referenced as many times as needed.
Then when the player places the bet, you can parse and assign to the variable. This would also be ideal with your player's chips.
class Program
{
private float _playersChips = 1000;
private float _currentBet;
static void Main()
{
//So on and so forth.
}
}
The only idea I have is to pass the variable By Reference from a method to another,
check this link
Wow, ok... so are you familiar with Global Variables?
Looking at your code, you're writing a console application in a procedural (rather than object-oriented) style... Whilst this can be done in C#, for larger applications, it can make code maintenance a big headache.
Regardless, I'll try and help you out...
Miles's answer is essentially using a Global Variable instead of a local one, which is a good suggestion when programming in a procedural style, however, another option for you is to make playerChips a reference method parameter (as suggested by Hussein) which can be passed (and modified) between methods... so (using both of their suggestions) your code would change to work as follows:
class Program
{
public static float _playerChips = 1000;
private static void Main()
{
Console.Write("Player's Chips: ");
Console.WriteLine(_playerChips);
Console.Write("1. Play Slot ");
Console.WriteLine("2. Exit");
choice(ref _playerChips);
result(_playerChips);
Console.ReadKey();
}
private static void choice(ref float playerChips)
{
int choice = int.Parse(Console.ReadLine());
if (choice == 1)
{
firstRandomNumberGenerator(ref playerChips);
}
if (choice == 2)
Environment.Exit(0);
}
private static void betValidation(ref float playerChips, ref float bet)
{
Console.WriteLine("Enter your bet: ");
bet = float.Parse(Console.ReadLine());
if ((bet <= 0) || (bet > playerChips))
{
Console.WriteLine("You did not enter a valid bet.\n");
Main();
}
}
private static void firstRandomNumberGenerator(ref float playerChips)
{
float bet = 0;
betValidation(ref playerChips, ref bet);
System.Random r = new System.Random();
int firstNumber = r.Next(2, 8);
int secondNumber = r.Next(2, 8);
int thirdNumber = r.Next(2, 8);
if (firstNumber == secondNumber || firstNumber == thirdNumber || thirdNumber == secondNumber)
playerChips = playerChips + (bet * 3);
Console.Write(firstNumber);
Console.Write(secondNumber);
Console.Write(thirdNumber);
Console.Write("\n");
}
private static void Update()
{
return;
}
private static void result(float playerChips)
{
return;
}
}
Now, I've also changed the choice() method you wrote to call Environment.Exit() and exit the program - the reason for this is, by executing Main() you're essentially calling methods within methods within methods and increasing your stack which will eventually lead to a Stack Overflow... I would consider changing your Main() method to use a loop based on choice() returning a result rather than just calling Main() from the betValidation method again (however I have not done this for you).
I am using recursion to add two numbers together, By adding 1 to the first input one at a time until I have reached the value of the second.
Why does this work...
private static int AddMethod(int input1, int input2)
{
if (input2 == 0)
{
Console.WriteLine(input1);
return (input1);
}
else
{
input1++;
input2--;
return AddMethod(input1, input2);
}
}
But not this..
private static int AddMethod(int input1, int input2)
{
if (input2 == 0)
{
Console.WriteLine(input1);
return (input1);
}
else
{
return AddMethod(input1++, input2--);
}
}
I am using Visual Studio 2010 and .Net 4.0
Because return AddMethod(input1++, input2--); first passes your inputs, and THEN increments and decrements.
Try
return AddMethod(++input1, --input2);
Post fix increment works by first "assigning" the value, then incrementing the value.
Compare:
int a = 1;
int b = 1;
int x = a++;
int y = ++b;
So in your case, the value you pass to AddMethod is the unchanged value, it modifies the value of input1 and input2 after they are passed.
Because the ++ and -- operators are executed after passing the values as parameters to the function.
Your code:
return AddMethod(input1++, input2--);
Is equal to:
int result AddMethod(input1, input2);
input1++;
input2--;
return result;
Instead of all this, you could use:
return AddMethod(++input1, --input2);
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.