C# Passing Parameters - c#

I try to transition a Monopoly Banking python programming I made into C#.
I used the main module is where I declare all my global variables, however, I don't quite understand how to call a module in another module without all the required variables passed into it.
https://pastebin.com/bVdt5nrP
For example on line 50 i try running SetCustom module however i don't have all the parameters that are required passed into MainMenu, I really don't wanna pass every Parameter into every module cause that just ends in mess and confusion. Is there away i can work around this or do i have to do everything messy?
Thanks in advance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MonopolyCSharpNonForm
{
class Program
{
static void Main(string[] args)
{
//Primary Settings
int StartingBallance = 2000;
int PassGo = 200;
int Bail = 50;
int IncomeTax = 100;
int SuperTax = 200;
string TaxLocation = 1; // 1 goes to the bank
//Players/Economy
string Player1 = "Player1";
string Player2 = "";
string Player3 = "";
string Player4 = "";
int Ballance1 = 2000;
int Ballance2 = 2000;
int Ballance3 = 2000;
int Ballance4 = 2000;
int FreeParking = 0;
string[] BankRupties = { };
MainMenu(); // Calling Main Menu
}
static void MainMenu()
{
Console.WriteLine("Welcome to Monpoly Banker V4");
Console.WriteLine("Would you to use the Default or Custom settings?"); //Ask for Default or Custom option
string LocalOption = Console.ReadLine(); //Record the option as a local variable 'LocalOption'
while (LocalOption != "Default" && LocalOption != "Custom")//Check if LocalOption is 'Default' or 'Custom'
{
Console.WriteLine("Niether option has been specified, type 'Default' or 'Custom'"); // If not state there is an Error.
LocalOption = Console.ReadLine(); //Record the input again.
}
if (LocalOption == "Custom") // Check if local variable is equal to custom.
{
SetCustom(ref StartingBallance, ref PassGo, ref Bail, ref IncomeTax, ref SuperTax, ref TaxLocation); //If it is run the SetCustom module below with the required parameters
}
else //Anything else it runs GettingNames module with required parameters
{
GettingNames(ref Player1, ref Player2, ref Player3, ref Player4);
}
}
static void SetCustom(ref int StartingBallance, ref int PassGo, ref int Bail, ref int IncomeTax, ref int SuperTax, ref string TaxLocation)
{
Console.WriteLine("\nHow much money is everyone starting with? "); // Ask for Starting Ballance
StartingBallance = Convert.ToInt32(Console.ReadLine()); // Change the StartingBallance to entered integer
Console.WriteLine("\nHow much money if you pass go? "); // Ask how much you get for passing go
PassGo = Convert.ToInt32(Console.ReadLine()); // change PassGo to entered integer
Console.WriteLine("\nHow much will bail cost? "); // Ash how much Bail is going to cost
Bail = Convert.ToInt32(Console.ReadLine()); // change Bail to entered integer
Console.WriteLine("\nHow much will income tax cost? "); // Ask how much Income Tax will cost
IncomeTax = Convert.ToInt32(Console.ReadLine()); // Change IncomeTax to entered Integer
Console.WriteLine("\nHow much will super tax cost? "); // Ask how much Super Tax will cost
SuperTax = Convert.ToInt32(Console.ReadLine()); // Record the entered integer
Console.WriteLine("\nDoes tax go to the bank for free parking? (1 = Bank | 2 = Free Parking)"); // Ask for where free parking will go (1/2 to make options easier)
TaxLocation = Console.ReadLine(); // Change TaxLocation to entered String
while (TaxLocation != "1" && TaxLocation != "2") // Check TaxLocation is either '1' or '2'
{
Console.WriteLine("Invalid Input. Try again."); // If not state its invalid input
TaxLocation = Console.ReadLine(); // Record entered Integer
}
GettingNames(ref Player1, ref Player2, ref Player3, ref Player4); // When done continue on to module Getting Names passing required parameters
}
static void GettingNames(ref string Player1, ref string Player2, ref string Player3, ref string Player4)
{
Console.WriteLine("\nWhat is Player1 name? "); // Ask Player1 name
Player1 = Console.ReadLine(); // Set Player1 to entered string
Console.WriteLine("\nWhat is Player2 name? "); // Ask Player2 name
Player2 = Console.ReadLine(); // Set Player1 to entered string
Console.WriteLine("\nWhat is Player3 name? "); // Ask Player3 name
Player3 = Console.ReadLine(); // Set Player1 to entered string
Console.WriteLine("\nWhat is Player4 name? "); // Ask Player4 name
Player4 = Console.ReadLine(); // Set Player1 to entered string
Console.WriteLine("All 4 player names have been entered."); // State all names entered and received
}
}
}

Personally, I think I would try breaking it down into individual classes first. For example, you could create a class called Game that had the settings for the game. The settings could be set through the constructor as default settings, and you can provide a custom constructor for setting individual things. Something like the following:
public class Game
{
public int PassGo;
public int Bail;
public ClassName()
{
PassGo = 200;
Bail = 50;
}
public ClassName(int customPassGo, int customBail)
{
PassGo = customPassGo;
Bail = customBail;
}
}
You could also set defaults for those parameters if you wanted by doing something like:
public ClassName(int customPassGo = 200, int customBail = 50)
{
PassGo = customPassGo;
Bail = customBail;
}
You can create objects out of the Players as well. Using objects can greatly simplify what you're trying to do here. Hope this helps!

Related

Return multiple values from one method C# [duplicate]

This question already has answers here:
Return multiple values to a method caller
(28 answers)
Closed 7 years ago.
Apologies on the duplicate question, I viewed similar Qs and just got confused. I have a method that is prompting a user to enter 5 different attribute values and would like to return the values chosen to be used for later decisions in the program.
while (true)
{
Console.Write("Please enter a value between 0-10 for ingenuity: ");
inputIngenuity = Console.ReadLine();
if (!UInt32.TryParse(inputIngenuity, out validIngenuity))
{
Console.WriteLine();
Console.WriteLine("Input was not a valid value for ingenuity.");
}
else if (validIngenuity < 0 || validIngenuity > 10)
{
Console.WriteLine();
Console.WriteLine("Input was not a valid value for ingenuity.");
}
else if (validIngenuity > (attributePoints - validStrength - validIntelligence - validPersonality - validSpeed))
{
Console.WriteLine();
Console.WriteLine("You do not have enough attribute points remaining.");
}
else break;
}
Console.WriteLine();
Console.WriteLine("You have " + (attributePoints - validStrength - validSpeed - validPersonality - validIntelligence - validIngenuity) + " attribute points remaining");
Console.WriteLine();
Console.WriteLine(String.Format("Strength Value = {0}", validStrength));
Console.WriteLine(String.Format("Speed Value = {0}", validSpeed));
Console.WriteLine(String.Format("Intelligence Value = {0}", validIntelligence));
Console.WriteLine(String.Format("Personaility Value = {0}", validPersonality));
Console.WriteLine(String.Format("Ingenuity Value = {0}", validIngenuity));
Console.WriteLine();
Console.WriteLine("These are your attributes!");
while (true)
{
Console.Write("Do you accept these? Type 1 for Yes, Type 2 for No. If No then choose again: ");
areYouHappyWithChoices = Console.ReadLine();
if (!UInt32.TryParse(areYouHappyWithChoices, out validChoices))
Console.WriteLine("Please try again. Enter 1 for Yes and 2 for No");
else if (validChoices > 2 || validChoices < 1)
Console.WriteLine("Please try again. Enter 1 for Yes and 2 for No");
else if (areYouHappyWithChoices == "2")
chooseAttributePoints(); //this method contains the whole routine
else
Console.WriteLine("We may now begin the game!");
break;
}
UInt32[] attributePointArray = new UInt32[5] { validStrength, validSpeed, validIntelligence, validPersonality, validIngenuity };
return attributePointArray;
The while statement for ingenuity is repeated in the method for the other 4 attributes and works without issues. I'm envisioning later code that would have different results based on how strong the user is for example. Am I going in the right direction by trying to put the values into an array? Thank you.
That would be one way to do it, however I think you'd be better off having a class or struct created to represent the data. This way you'll keep the "strong typey ness" and context of what your data is, rather than simply an array index.
example:
public class Person
{
public int Strength { get; private set; }
public int Speed { get; private set; }
public int Intel { get; private set; }
public int Personality { get; private set; }
public int Ingenuity { get; private set; }
public Person (int strength, int speed, int intel, int personality, int ingenuity)
{
this.Strength = strength;
this.Speed = speed;
this.Intel = intel;
this.Personality = personality;
this.Ingenuity = ingenuity;
}
}
Then your assignment to array:
UInt32[] attributePointArray = new UInt32[5] { validStrength, validSpeed, validIntelligence, validPersonality, validIngenuity };
return attributePointArray;
Gets updated to:
return new Person(validStrength, validSpeed, validIntelligence, validPersonality, validIngenuity);
and your return type needs to be changed from uint[] to Person
This way, rather than having to remember that returnedArray[1] is Speed (or whatever) - you would simply use returnedPerson.Speed.
You should create an object type that wraps the attributes you want to return. The return type of your method will be your newly-created object type.

C# Need to set up a loop to reject invalid user input (below 1/ above 5) How can I do that? New to coding, making cinema entry app

namespace ConsoleApplication2
{
class Program
{
static void Main()
{
Console.WriteLine("Welcome to our Multiplex");
Console.WriteLine("We are presently Showing:");
Console.WriteLine("1.Legend");
Console.WriteLine("2.Macbeth");
Console.WriteLine("3.Everest");
Console.WriteLine("4.A Walk In the Woods");
Console.WriteLine("5.Hotel Transylvania");
Console.WriteLine("Enter the number of the film you wish to see?");
{
string moviestring = Console.ReadLine();
int movie = int.Parse(moviestring);
Here is solution I could suggest for your case:
static void Main(){
bool flag0 = true; //initialize tracking bool value to exit loop when needed
int result;
Console.WriteLine("Welcome to our Multiplex");
Console.WriteLine("We are presently Showing:");
Console.WriteLine("1.Legend");
Console.WriteLine("2.Macbeth");
Console.WriteLine("3.Everest");
Console.WriteLine("4.A Walk In the Woods");
Console.WriteLine("5.Hotel Transylvania");
do //do while loop suits this case best as it does check the value on the end
{
Console.WriteLine("Enter the number of the film you wish to see?");
string moviestring = Console.ReadLine();
int.TryParse(moviestring, out result); //does try-catch check so it wont crash on the run-time
if (result <= 5 && result >= 1) //logical check if value is correct
flag0 = false; //exits the loop
//do true logic....
else
Console.WriteLine("Incorrect value. Try again.");
//do false logic
} while (flag0);
}

Using Method and passing values to main method

So I have a question that ask for a Movies method, to accept a name as string and a integer(represents time in minutes). So if you call this method without an integer minutes is set to a default of 90. Then the main method shows that you can call the movies method with only a string as well show you can call it with a string and integer.
static void Main()
{
Console.WriteLine("Movie title is {0}, and time is", MovieListing("x") );
}
private static string MovieListing(string name, int defaultTime = 60)
{
string Name, stringTime;
int time;
bool isValid;
Console.Write("What is the name of the movie?");
Name = Console.ReadLine();
Console.Write("What is the time of the movie? Default is 90 if left blank");
stringTime = Console.ReadLine();
time = Convert.ToInt32(stringTime);
}
So Im left blank thinking how to get the program to tell if the user entered a time int and use that or if they are just using the default 90 and passing them back to the main method sorry if the codes a mess was trying different ways without much success
You can use the ternary operation to check if the entered value is empty:
time = string.IsNullOrEmpty(stringTime) ? defaultTime : Convert.ToInt32(stringTime);
It will parse the stringTime if filled, else it will take the default.
Here's a better way to do this, using a simple Movie object to hold the values. This should print out two hardcoded lines to demo and then ask the user for input:
private class Movie
{
private readonly int _defaultLength = 90;
public string Title { get; set; }
public int Length { get; set; }
// constructor without length - use default length
public Movie(string title)
{
this.Title = title;
this.Length = _defaultLength;
}
// constructor with both properties
public Movie(string title, int length)
{
this.Title = title;
// make sure Length is valid
if (length > 0)
this.Length =length;
else
this.Length = _defaultLength;
}
}
static void Main()
{
// make a Movie object without length
var shortMovie = new Movie("Zombieland");
// make a Movie object and specify length
var longMovie = new Movie("Lawrence of Arabia", 216);
Console.WriteLine("{0} is {1} minutes long", shortMovie.Title, shortMovie.Length);
Console.WriteLine("{0} is {1} minutes long", longMovie.Title, longMovie.Length);
// get input from user: title
Console.Write("What is the name of another movie?");
var userTitle = Console.ReadLine();
// get input from user: length
Console.Write("What is the length of {0}? Default is 90 if left blank", userTitle);
var userTime = Console.ReadLine();
// try to convert user input to an int and call Movie constructor to create a new object
int userTimeConverted = 0;
Movie userMovie;
if (Int32.TryParse(userTime, out userTimeConverted))
{
// make a new Movie object with the user's input
userMovie = new Movie(userTitle, userTimeConverted);
}
else
{
// make a new Movie object without the user's input
userMovie = new Movie(userTitle);
}
Console.WriteLine("{0} is {1} minutes long", longMovie.Title, longMovie.Length);
}
By building a separate Movie object, we can move most or all of the logic needed for storing a default length and checking to see if the length is valid out of the Main() method. This should hopefully be much cleaner and easier to read.
As an added bonus, we can create as many instances of Movie as we want - as demonstrated in the above code.
Set the default value to something you wouldnt expect the user to enter and detect and handle that.
private static string MovieListing(string name, int defaultTime = -1)
{
var isDefaultUsed = false;
if (defaultTime = -1)
{
isDefaultUsed = true;
defaultTime = 60;
}
string Name, stringTime;
int time;
bool isValid;
Console.Write("What is the name of the movie?");
Name = Console.ReadLine();
Console.Write("What is the time of the movie? Default is 90 if left blank");
stringTime = Console.ReadLine();
time = Convert.ToInt32(stringTime);
}

Confused about how to use return in c#

Ai'm new here and new in programming as well. I'm sorry if this question is really childish but i'm having some trouble using return type in a simple c# program.
Here is my code file, at d == 2 in AccountTest class, I want the withdrawal process to start over again but this time not asking the user to enter the account balance. A friend advice to use while loop but I have no idea how to use while loop over here. Thanks in advance. :)
using System;
public class Account
{
public static void Main(string[] args)
{
Console.Write("Enter your account balance: ");
int AccountBalance = Convert.ToInt32(Console.ReadLine());
Account.Debit(AccountBalance);
}
public static void Debit(int AccountBalance)
{
Console.Write("\n\nEnter the amount you want to withdraw in Rs: ");
int WithdrawalAmount = Convert.ToInt32(Console.ReadLine());
AccountTest.DebitTest(AccountBalance, WithdrawalAmount);
}
}
And my Account class
public class AccountTest
{
public static int DebitTest(int AccountBalance, int WithdrawalAmount)
{
if (WithdrawalAmount > AccountBalance)
{
Console.WriteLine("\n\nDebit amount exceeded account balance.");
Console.ReadLine();
return 0;
}
else if (WithdrawalAmount <= 0)
{
Console.WriteLine("\n\nError. Incorrect amount.");
Console.ReadLine();
return 0;
}
else
{
int newBalance = AccountBalance - WithdrawalAmount;
Console.WriteLine("\n\nWithdrawal was successful. Thankyou for using our services.\n\nPress 1 to exit, 2 to withdraw again, 3 to check your account balance.\n");
int InputNumber = Convert.ToInt32(Console.ReadLine());
if (InputNumber == 1)
{
Console.ReadLine();
return 0;
}
else if (InputNumber == 2)
{
return WithdrawalAmount;
}
else if (InputNumber == 3)
{
Console.WriteLine("\n\nYour remaining account balance is: {0}", newBalance);
Console.ReadLine();
return 0;
}
}
return 0;
}
}
Really the code should be refactored. Treating an Account like a thing makes more sense, in that it should be it's own object, and you should tell it what to do:
public class Account
{
public int Balance { get; set; }
public Account(int startBalance)
{
Balance = startBalance;
}
public void Debit(int amount) { Balance -= amount; }
public void Credit(int amount) { Balance += amount; }
}
Now, you can ask the user what they want to do with their Account, and you have room to add multiple accounts. So the program may look like:
int startingAmount = int.Parse(Console.ReadLine());
var account = new Account(startingAmount);
Console.WriteLine("1 to credit, 2 to debit, 0 to exit");
var input = int.Parse(Console.ReadLine());
while (input != 0)
{
//manipulate account
}
I'd start by reading up about static vs instance objects
first of, welcome to the coding community there is no childish question feel free to ask when ever you need, there some who will answer you with "google has the answer" but no worries a lot of other will help you, i saw you already selected an answer but ill add my point of view for you and the rest of new programmers.
a. if your new to codding never start with code it will only complicate things, instead start with a flow chart that illustrates what you to achieve from the program and from each component ( classes,functions etc. ) after you got that, its a lot easier to transform it to code, you can try using this site
it seems to be very user friendly and will draw you flow charts with the correct format.
b. like people here said before me never use variable like a,b,c because the next day youll try to continue where you left off and you will forget what you meant.
c. try to think of ways to use code to prevent repeating yourself.
d. using hard coded values is bad practice (hard coded means this:
return "this value to return is hard coded and will never change";
)
by the time i got to answer your question i already saw #Jonesy answer which is right and like what
i wanted to suggest so ill leave you with his answer.
hope this helps someone :)
The loop can be implemented in the Debit method:
public static void Debit(int AccountBalance)
{
int result = 0;
do
{
Console.Write("\n\nEnter the amount you want to withdraw in Rs: ");
var WithdrawalAmount = Convert.ToInt32(Console.ReadLine());
result = AccountTest.DebitTest(AccountBalance, WithdrawalAmount);
} while (result != 0);
}
You should read up on while loops. Basically what you'd want is the method to return a number that decides what the program is supposed to do next, or when it should end. Think of the loop as your engine that states "As long as [chosen key] is not pressed, keep doing something".
A small example, with [chosen key] being 1, would be:
int choice = 0;
int balance = 100;
while (choice != 1) {
Console.WriteLine("Enter withdraw amount");
string userInput = Console.ReadLine();
// This will crash the program if the user enters text.
// Used for demonstration only. int.TryParse is preferred.
int value = int.Parse(userInput);
choice = AccountTest.DebitTest(balance, value);
}
class AccountTest {
public static int DebitTest(int AccountBalance, int WithdrawalAmount)
{
// do the test if the debit is OK
//..........
// At the end, you can do this. This till return the value entered and
// choice will be given a new value. If it was 1, the program will end.
// NOTE: It's not safe to use convert as
// it will crash the program if the user enters text.
return Convert.ToInt32(Console.ReadLine());
}
}
Note that this is not a functional ATM-program, as the balance never gets updated. I leave that for you to solve since I'm guessing this is for a class in programming =)
Well, this is my version of your program. I changed the behavior a bit (like asking again when the value is invalid). It's not perfect; for example, the messages and the RequestDebit method should be handled outside the Account class, perhaps in an AccountHandler class, but all this might be overkill for this simple exercise. Anyway I hope you find it useful:
public class Account
{
public int Balance { get; set; }
public Account(int startingBalance)
{
this.Balance = startingBalance;
}
private bool Debit(int amount)
{
if (amount <= 0)
{
Console.WriteLine("\n\nError. Incorrect amount.");
return false;
}
if (amount > this.Balance)
{
Console.WriteLine("\n\nDebit amount exceeded account balance.");
return false;
}
this.Balance -= amount;
Console.WriteLine("\n\nWithdrawal was successful. Thankyou for using our services.");
return true;
}
public void RequestDebit()
{
bool success;
do
{
Console.Write("\n\nEnter the amount you want to withdraw in Rs: ");
int withdrawalAmount = Convert.ToInt32(Console.ReadLine());
success = this.Debit(withdrawalAmount);
} while (!success);
}
}
class Program
{
static void Main(string[] args)
{
int accountBalance;
do
{
Console.Write("Enter your account balance: ");
accountBalance = Convert.ToInt32(Console.ReadLine());
} while (accountBalance <= 0);
var myAccount = new Account(accountBalance);
myAccount.RequestDebit();
int inputNumber;
do
{
Console.WriteLine("\n\nPress 1 to exit, 2 to withdraw again, 3 to check your account balance.\n");
inputNumber = Convert.ToInt32(Console.ReadLine());
switch (inputNumber)
{
case 2: myAccount.RequestDebit();
break;
case 3:
Console.WriteLine("\n\nYour remaining account balance is: {0}", myAccount.Balance);
break;
}
} while (inputNumber != 1);
}
}

Difficulty with passing arrays and manipulating data in arrays (Homework) c#

So I am doing a Homework assignment for c#. The assignment requires the use of 2 arrays, one to hold names and the other to hold scores. We are then to calculate the average score, display the below average scores, and display the scores according to name. I am having a significant amount of difficulty passing the arrays by reference/value in order to use the data in them and maintain my code using separate modules. The arrays have to hold up to 100 individual pieces of data.
class Program
{
static void Main(string[] args)
{
string[] playerNames = new string[100];
int[] playerScores = new int [100];
int numPlayers = 0;
double averageScore;
DisplayData(playerNames);
}
static void InputData(string[] playerNames, int[] playerScores, ref int numPlayers)
{
string playerName;
do
{
int i = 0;
Console.WriteLine("Enter the name of the player...Enter \"Q to exit...");
playerName = Console.ReadLine();
if (playerName == "Q" || playerName == "q")
Console.WriteLine("No further user input needed...\n");
else
playerNames[i] = playerName;
Console.WriteLine("Enter the score of the player...");
int playerScore = Convert.ToInt32(Console.ReadLine());
playerScores[i] = playerScore;
numPlayers += i;
i++;
}
while (playerName != "Q");
}
static void CalculateAverageScore(int[] playerScores, ref int averageScore)
{
InputData(playerScores);
InputData(ref numPlayers);
int averageScores = 0;
averageScores = playerScores / numPlayers;
}
The biggest question I have is that I cannot seem to pass the array data. I am plagued by "No overload method for "Input Data" or whatever method I am using. So I'm curious as to how I can pass the array data to another method.
Since this is homework, I won't give you the full answer, but here is a way forward.
Instead of using the ref keyword, just pass the array into the method. Have the method return an int instead of void. Calculate the average within the method and have the final line of the method return the int that you've calculated
static int CalculateAverageScore(int[] playerScores)
{
// calculate average
return average; // the int you've calculated.
}
Call the method from the main, when you need to acquire the average.
Also, are you missing some braces { } for the 6 lines that come after your else statement?

Categories

Resources