I have typed up some code to try and practice what I have learned in my programming course. Something is wrong with my logic as I am not getting the answer I am supposed to get.
I have searched and google and rewatched the training videos but nothing seems to help.
namespace TenPinBowling
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.Write("Would you like to bowl, Y or N: ");
var answer = Console.ReadLine();
if (answer == "n")
{
Console.WriteLine("Thanks for playing, press any to exit :)");
Console.ReadKey();
break;
}
Score();
}
}
static void Score()
{
{
Random pins = new Random();
var pinsKnockedDown = pins.Next(0, 10);
//var totalScore = 0;
Console.WriteLine("You bowled a: " + pinsKnockedDown);
//var result = totalScore + pinsKnockedDown;
Console.WriteLine("You're total score is: " + Tally(pinsKnockedDown));
}
}
static int Tally(int score)
{
{
int result = 0;
result = result + score;
return result;
}
}
}
}
I was hoping my second method would keep a running total of my score but it resets to the individual score every time.
In
static int Tally(int score)
{
{
int result = 0;
result = result + score;
return result;
}
}
you create a new local variable result each time you invoke the method, so the record of past scores is lost. Making result a field of the class would allow it to persist for the duration of the game. A minimal code change might be:
private static int result = 0;
static int Tally(int score)
{
result = result + score;
return result;
}
I would guess you always need to keep track of your total score, if it should not reset. Right now you always add the current score to zero (in Tally). If you put int result outside of tally it should keep track accordingly.
Related
I'm writing a program that displays a fast food menu and it allows the user to select an item. Then, the user enters the quantity of that item, and can continue selecting items with specific quantities until done. What I'm having trouble with is finding out how to calculate a running total. I am new to c# so I only know the basics. What is the best way to keep track of the running total while using multiple methods? In addition, I'm open to any criticism in my code. Thank you in advance.
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
bool ordering = true;
string userInput;
double itemPrice;
double itemQuantity;
double subTol;
string response;
void pricing()
{
Console.Write("Enter option 1, 2, 3: ");
userInput = Console.ReadLine();
switch (userInput)
{
case "1":
itemPrice = 3.00;
Console.WriteLine("You have picked a burger.");
break;
case "2":
itemPrice = 1.50;
Console.WriteLine("You have picked fries.");
break;
case "3":
itemPrice = 1.00;
Console.WriteLine("You have picked a soda.");
break;
default:
Console.WriteLine("That is not on our menu.");
pricing();
break;
}
}
void quantity()
{
Console.Write("Enter quantity: ");
itemQuantity = Convert.ToDouble(Console.ReadLine());
}
void subTotal()
{
subTol = itemQuantity * itemPrice;
Console.WriteLine();
Console.WriteLine("Your Subtotal: " + subTol);
}
while (ordering)
{
Console.WriteLine("What would you like from our menu?");
Console.WriteLine("\n1. Burger ($3.00) \n2. Fries ($1.50) \n3. Soda ($1.00)");
Console.WriteLine();
pricing();
quantity();
subTotal();
Console.Write("Would you like anything else? Y/N: ");
response = Console.ReadLine();
response = response.ToUpper();
if (response == "Y")
{
ordering = true;
}
else
{
ordering = false;
Console.WriteLine("Enjoy your meal!");
}
}
}
}
}
First of all, for the
If(response==“Y”)
Part you can actually just say
ordering = response == “Y”;
Also, this would only accept uppercase y. String.EqualsIgnoreCase() or something similar would probably do a better job
ordering = response.equalsIgnoreCase(“Y”);
You could keep a list of how many of each item the person has ordered, like
Int burgers = 0; and so on.
Then for the total, you could get 3*burgers + 1.5*fries and so on. However, if you want custom orders, using a struct might be better. For example, a struct could contain a type(burger or fries) and a price, depending on how many additions they have. You could also just add the price of each item to a total every time you order. This seems like a fun project, and I hope I could help!
For keeping track of total, the best approach would be to have a list of ordered items with their quantities, where you go and put each order from the user.
When you want to calculate the subtotal or total, you just go and compute from the list.
Here are some insights on how you can accomplish that, with some changes to the code you shared. Check the comments for details and reasoning.
namespace ConsoleApp1{
// creating record classes to store structured data
record MenuItem(string Product, decimal Price);
record Order(MenuItem Item, int Quantity);
class Program {
static void Main(string[] args) {
// better to keep your menu options & prices in a central place,
// instead of hardcoding them everywhere
List<MenuItem> menu = new() {
new ("Burger", 3.00M),
new ("Fries", 1.50M),
new ("Soda", 1.00M),
};
// this is a list to store the ordered items so far
List<Order> orders = new();
// moved most of the procedures to separate functions
do {
PrintMenu(menu);
var item = InputItem(menu);
var quantity = InputQuantity();
orders.Add(new Order(item, quantity));
PrintSubTotal(orders);
} while (CheckIfContinue());
PrintTotal(orders);
ByeBye();
}
static void PrintMenu(List<MenuItem> menu) {
// print each menu entry in a loop
Console.WriteLine("What would you like from our menu?");
for (int i = 0; i < menu.Count; i++) {
// adding 1 to the index for printing, because in c# indexes start at 0
Console.WriteLine($"{i + 1}: {menu[i].Product} (${menu[i].Price})");
}
Console.WriteLine();
}
static MenuItem InputItem(List<MenuItem> menu) {
// enter a loop, will be broken only if the input is correct
while (true) {
Console.Write($"Enter option: 1 to {menu.Count}: ");
if (int.TryParse(Console.ReadLine(), out int i) && i > 0 && i <= menu.Count) {
// must subtract 1 from the index, because indexes start from 0 in c#
Console.WriteLine($"You have picked {i}: {menu[i - 1].Product}.\n");
// if the input is a valid int
return menu[i - 1];
}
Console.WriteLine("That is not in our menu.\n");
}
}
static int InputQuantity() {
// same thing here, will repeat the loop unless the input is valid
while (true) {
Console.Write("Enter quantity: ");
if (int.TryParse(Console.ReadLine(), out int i) && i > 0) {
return i;
}
Console.WriteLine("Invalid quantity.\n");
}
}
static void PrintSubTotal(List<Order> orders) {
// using LINQ to iterate the list of orders sum up the prices x quantities
Console.WriteLine($"Your Subtotal: ${orders.Sum(o => o.Item.Price * o.Quantity)}\n");
}
static bool CheckIfContinue() {
Console.Write("Would you like anything else? Y/N: ");
// will return True if the input is y
return Console.ReadLine()?.Trim().ToUpper() == "Y";
}
static void PrintTotal(List<Order> orders) {
Console.WriteLine($"Your Order:");
foreach (var order in orders) {
// subtotal for each order item
Console.WriteLine($"{order.Item.Product, -10} x{order.Quantity, -4}: ${order.Item.Price * order.Quantity}");
}
// total for the whole order
Console.WriteLine($"---------- Total: ${orders.Sum(o => o.Item.Price * o.Quantity)}\n");
}
static void ByeBye() {
Console.WriteLine("Enjoy your meal!");
}
}
}
I am writing a program that will ask the user to enter a number. I have coded that, but what I am struggling to add is a part where it will ask the user again if they entered a character or never answered the question in the first place. I want this done to all my questions that I ask them since they are all asking for an Integer.
using System;
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("---welcome to split my bill---");
Console.Write("What is the total bill?: £");
float bill_total = Convert.ToSingle(Console.ReadLine());
Console.Write("How many people are sharing?:");
int people = Convert.ToInt32(Console.ReadLine());
Console.Write("What percentage tip would you like to leave?:");
float tip_percentage = Convert.ToSingle(Console.ReadLine());
float percentage_decimal = tip_percentage/100;
float tip_total = bill_total * percentage_decimal;
bill_total = bill_total + tip_total;
float CostPerPerson = bill_total/people;
Console.WriteLine("Total Bill including tip is: £"+bill_total);
Console.WriteLine("Total cost per person is: £"+CostPerPerson);
}
}
any help?
Since you are learning C#, think a bit more general and write a function to handle user inputs with repeats if they type something wrong.
class Program
{
static void Main(string[] args)
{
float totalBill = AskForNumber("What is the total bill?");
}
static float AskForNumber(string prompt)
{
while (true)
{
Console.WriteLine(prompt);
var input = Console.ReadLine();
if (float.TryParse(input, out float value))
{
return value;
}
Console.WriteLine("Invalid Input. Try again.");
}
}
}
The problem with the above method is that the user has no way of exiting the program unless they press Ctrl-C which is not very graceful.
You need to learn of about out parameters for functions, and then you can write the function to input a value and return true if the program should proceed, or false if it needs to exit. The value itself is assigned to the variable designated with the out keyword.
Below is an example of the whole process. Each step proceeds only if the previous function returned true. If a user enters a blank line, then the program will exit as the return value is going to be 'false' and the program is not going to continue inside the if() statement.
class Program
{
static void Main(string[] args)
{
if (AskForNumber("What is the total bill?", out float totalBill))
{
if (AskForInteger("How many people are sharing?", out int people))
{
if (AskForNumber("What percentage tip would you like to leave?", out float tipPercent))
{
float tip_total = totalBill * (tipPercent/100);
totalBill += tip_total;
float costPerPerson = totalBill/people;
Console.WriteLine("Total Bill including tip is: £"+totalBill);
Console.WriteLine("Total cost per person is: £"+costPerPerson);
}
}
}
}
static bool AskForNumber(string prompt, out float value)
{
while (true)
{
Console.WriteLine(prompt);
var input = Console.ReadLine();
if (float.TryParse(input, out value))
{
return true;
}
if (input.Length == 0)
{
return false;
}
Console.WriteLine("Invalid Input. Try again.");
}
}
static bool AskForInteger(string prompt, out int value)
{
while (true)
{
Console.WriteLine(prompt);
var input = Console.ReadLine();
if (int.TryParse(input, out value) && value>0)
{
return true;
}
if (input.Length == 0)
{
return false;
}
Console.WriteLine("Invalid Input. Try again.");
}
}
}
using System;
namespace VSCode
{
class Program
{
static void Main()
{
//Terminal Settings
Console.Title = "Dungeon Crawler";
Console.WindowHeight = 40;
Console.WindowWidth = 150;
//vars
int playerHP = 10;
string armorType = "Leather Tunic";
int armorValue = 1;
string weaponType = "Wooden sword";
int weaponDMG = 2;
int gold = 100;
string enemyType;
int enemyHP;
int enemyArmor;
int enemyDMG;
Console.WriteLine("Type 'start' to start the game");
if(Console.ReadLine() == "start")
{
DungeonCrawlersIntro();
}
void DungeonCrawlersIntro()
{
//intro
Console.WriteLine("---Welcome To Dungeon Crawler!");
Console.WriteLine("---Press Any Key to get the next line---");
Console.ReadKey(true);
Console.WriteLine("---Dungeon Crawler is a game made by YaLocalJesterBoi AKA Addi-O---");
Console.ReadKey(true);
Console.WriteLine("---It is a simple pure text RPG that I am working on alone with minimal yt help and the like. its just me making this thing for fun---");
Console.ReadKey(true);
Console.WriteLine("---Anyways, enjoy!");
Console.ReadKey(true);
Console.WriteLine("---You are an adventurer who has come from far away in order defeat the dungeon of the gods, 'Malakeith'---");
Console.ReadKey(true);
Console.WriteLine("--Like most other adventurers, all you want is money and loot. To be the strongest of them all---");
Console.ReadKey(true);
Console.WriteLine("---Currently you have " + playerHP + " HP " + armorType + " armor type that gives " + armorValue + " armor and " + gold + " Gold along with a " + weaponType + " that deals " + weaponDMG + " Attack damage---");
Console.ReadKey(true);
Console.WriteLine("---The dungeon Malakeith is quite famous and has a dfficulty all the from 'F' rank adventurers adventuring, to S class adventurers comeing to beat the dungeon entirely---");
Console.ReadKey(true);
Console.WriteLine("---You, just like many other ambitious adventurers just want some money and loot to live your life lavishly---");
Console.ReadKey(true);
Console.WriteLine("---The Dungeon itself is extremely popular, garnering people from all pver the world to explore it, but the selling point isn't just the dungeon itself, but the city that has been created around it. Malakeith city is well known as the best place to buy and sell anything obtained, or used in adventuring, all the way from a godly sword, to a simple health potion sold by every peddler---");
Console.ReadKey(true);
Console.WriteLine("---Type '/dungeon' to go to the dungeon---");
Console.WriteLine("---If you dont comply the game will simply shut down---");
if(Console.ReadLine() == "/dungeon")
{
Dungeon();
}
else
{
Console.WriteLine("---Since you were messing around, you got mugged and killed---");
Console.ReadKey();
playerHP = playerHP - 10;
if(playerHP < 1)
{
return;
}
}
}
void Dungeon()
{
Console.WriteLine("---You have entered the very first floor of the Malakeith dungeon!---");
Console.ReadKey(true);
Console.WriteLine("As you enter, you get transported into an iteration of the dungeon, totally randomized each time for every adventurer or party---");
Console.ReadKey(true);
Console.WriteLine("---The inside seem to be meadows, stretching on beyond the horizon---");
Console.ReadKey(true);
Console.WriteLine("---The only residents of this area are slimes and some other petty creatures such as goblins and the occasional goblin leader---");
Console.ReadKey(true);
Console.WriteLine("---One such resident of this area has decided to have a shit at killing you---");
Console.ReadKey(true);
enemyRoll();
}
void enemyRoll()
{
Random enemyRollValue = new Random();
int roll = 0;
roll = enemyRollValue.Next(1,7);
while(roll > 3)
{
goblinFight();
}
else
{
slimeFight();
}
}
void goblinFight()
{
enemyType = "goblin";
enemyHP = 5;
enemyArmor = 0;
enemyDMG = 4;
Console.WriteLine("---This resident that has come to fight is a " + enemyType + "---");
Console.ReadKey(true);
Console.WriteLine("It has " + enemyHP + " HP");
Console.ReadKey(true);
Attack();
}
void slimeFight()
{
enemyType = "slime";
enemyHP = 3;
enemyArmor = 0;
enemyDMG = 2;
Console.WriteLine("---This resident that has come to fight is a " + enemyType + "---");
Console.ReadKey(true);
Console.WriteLine("It has " + enemyHP + " HP");
Console.ReadKey(true);
}
void Attack()
{
enemyHP = (enemyHP + armorValue) - (weaponDMG + extraATK);
}
void AddAttack()
{
Random addAttack = new Random();
int extraATKRoll = 0;
extraATKRoll = addAttack.Next(1,10);
while(extraATKRoll >= 5)
{
public static int extraATK = 1;
}
}
}
}
}
it's a hundred something line of code that i've written for my pet project, dungeon crawlers. It's just a simple pure text RPG game made in VSCode alone that i've been making to brush up my skills and typing speed and to make me just more comfortable with VSCode.
there's a couple errors that i'm having that i cant seem to find the answers to. I have tried the stuff i found online, but to no avail.
the error messages are as follows:
} expected [VSCode]
} expected [VSCode, VSCode, VSCode]
Type or namespace definition, or end-of-file expected [VSCode]
Type or namespace definition, or end-of-file expected [VSCode]
Type or namespace definition, or end-of-file expected [VSCode]
The variable 'enemyArmor' is assigned but its value is never used [VSCode]
The variable 'enemyDMG' is assigned but its value is never used [VSCode]
The local function 'AddAttack' is declared but never used [VSCode]
The strange thing with enemy armor is that there are other ints and and strings that are declared and used in the exact same place with no difference(that i see) in use or writing. the main issue is with the '}' because previously the only problem was that there was 1 where it required 1 extra '}' because i messed up, but after that as i wrote more and more code, there were more of these popping up. i tried whatever i could find and havent been able to get further ahead. i have copy pasted some of my code from a previous iteration of the game that i scrapped for too much sphaghetti.
Do keep in mind that i'm pretty new to coding and not very good at it, so please put your answers in terms a new coder would understand
Let's go through this one at a time:
void enemyRoll()
{
Random enemyRollValue = new Random();
int roll = 0;
roll = enemyRollValue.Next(1,7);
while(roll > 3)
{
goblinFight();
}
else
{
slimeFight();
}
}
There's an else that isn't prefixed with an if block. Change the while to an if block to resolve the issue
void enemyRoll()
{
Random enemyRollValue = new Random();
int roll = 0;
roll = enemyRollValue.Next(1,7);
if(roll > 3)
{
goblinFight();
}
else
{
slimeFight();
}
}
Next error:
void AddAttack()
{
Random addAttack = new Random();
int extraATKRoll = 0;
extraATKRoll = addAttack.Next(1,10);
while(extraATKRoll >= 5)
{
public static int extraATK = 1;
}
}
You cannot create a global variable (i.e. extraATK) inside a method. Define extraATK below int enemyDMG like int extraATK = 0;
After converting the while to if, the function should look like:
New function should look like:
void AddAttack()
{
Random addAttack = new Random();
int extraATKRoll = 0;
extraATKRoll = addAttack.Next(1,10);
if(extraATKRoll >= 5)
{
extraATK = 1;
}
}
This should resolve the issues.
Firstly, you have the following; you can't else a while statement
while(roll > 3)
{
goblinFight();
}
//Comment out this mess, or do something else with it
//else
//{
// slimeFight();
//}
Secondly, you are trying to declare a static member inside a while statement.. Once again it doesn't make sense:
while(extraATKRoll >= 5)
{
// this doesn't make sense, comment it out
//public static int extraATK = 1;
}
You need to put it directly in the class (at least):
class Program
{
public static int extraATK = 1;
Things go pear-shaped at that enemyRoll method. You have a while statement followed by an else statement. You seem to be missing an if somewhere but it's impossible to know for sure what you intended there.
Changing the while to an if fixed that issue but you still have another problem. In the AddAttack method you have another while loop and inside that you try to declare a static field, which makes no sense at all.
I'm working on an assignment, where I have to make an application where you can throw 1-4 dice. The results are then added to a list.
However, if any of them is a 6, that one isn't added to the list, instead 2 additional dice are thrown.
As long as a die returns a 6, 2 more dice have to be thrown, until no die returns a 6.
Does anyone here know how to solve this? My programming skills are really basic, and I haven't used them much since last year.
for (int i = 0; i < qty; i++)
{
int diceNr = RollDice(random);
dicelist.Add(diceNr);
Console.WriteLine(diceNr);
if (diceNr == 6)
{
dicelist.Remove(diceNr);
Console.WriteLine("You got a six, that means you get 2 extra throws!");
for (int x = 0; x < 2; x++)
{
diceNr = RollDice(random);
dicelist.Add(diceNr);
}
You can try using a while loop as follows:
int i = quantity; #initialize a variable to your maximum number of throws
while(i > 0){ #until you have throws yet
i--; #this is the equivalent of one throw
int diceNr = RollDice(random);
dicelist.Add(diceNr);
Console.WriteLine(diceNr);
if(diceNr == 6){
Console.WriteLine("You got a six, that means you get 2 extra throws!");
i = i + 2; #add your bonus throws
}
}
You can use a while loop that exits once you are out of rolls. If you roll a six, add two more to the remaining quantity otherwise add the rolled value to the list.
int qty = 6;
// decrement remaining quantity each iteration
// until zero rolls remain
while(qty-- > 0)
{
int diceNr = RollDice(random);
Console.WriteLine(diceNr);
if (diceNr == 6)
{
// rolled six, add two more rolls
Console.WriteLine("You got a six, that means you get 2 extra throws!");
qty += 2;
}
else
{
// not six, add to list
dicelist.Add(diceNr);
}
}
// output all the non-six values
var allRolls = string.Join(",", diceList);
Console.WriteLine("All rolls: " + allRolls);
You could also do this with recursion (though I don't recommend it for this problem):
private static void Play(List<int> diceList, Random random, int rolls)
{
// base case, no rolls remain
if (rolls == 0)
return;
int diceNr = RollDice(random);
Console.WriteLine(diceNr);
if (diceNr == 6)
{
Console.WriteLine("You got a six, that means you get 2 extra throws!");
// add one to rolls since we are "reusing" this slot
// adding two would give us one more roll than we really want
rolls++
}
else
{
diceList.Add(diceNr);
// decrement rolls by one
rolls--;
}
// recursively call Play with updated roll count
// which is either original + 1 OR original - 1
Play(diceList, random, rolls);
}
private static int RollDice(Random r)
{
return r.Next(1, 7);
}
public static void Main()
{
var diceList = new List<int>();
var random = new Random();
int qty = 6;
Play(diceList, random, qty);
// output all the non-six values
var allRolls = string.Join(",", diceList);
Console.WriteLine("All rolls: " + allRolls);
}
My (readable) solution would look like:
class Program
{
static void Main(string[] args)
{
var game = new Game(4);
game.Play();
}
}
public class Game
{
private readonly int _noOfDices;
private readonly List<int> _result;
private readonly Random _random = new Random();
public Game(int noOfDices)
{
_noOfDices = noOfDices;
_result = new List<int>();
}
public void RollDice()
{
var no = _random.Next(1, 7);
if (no == 6)
{
RollDice();
RollDice();
}
else
{
_result.Add(no);
}
}
public void Play()
{
for (var i = 1; i <= _noOfDices; i++)
{
RollDice();
}
Console.WriteLine($"Output: {string.Join(',',_result)}");
}
}
Output:
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);
}
}