Improving code, added Goto or loop fuction - c#
I am trying to add a Goto or like function in my code. This game is based on the hammurabi game. I am trying to remove the sections in my code where it says "Please reset" and follows back to the question.
Also once the game is completed I am looking it to loop back and add a value to the year but also keep values from the orginal game.
using System;
namespace Game2
{
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int land = 1000, people = 100, landprice = rnd.Next(17, 26);
int foodin = 0, landin = 0, landout = 0, seeds = 0;
int foodcost = 20, food = 2800, totalfoodcost = 0;
int year = 0;
Console.WriteLine("TRY YOUR HAND AT GOVERNING ANCIENT SUMERIA");
Console.WriteLine("SUCCESSFULLY FOR A 1 YEAR TERM OF OFFICE.");
Console.WriteLine();
Console.WriteLine("HAMURABI: I BEG TO REPORT TO YOU,");
Console.WriteLine();
Console.WriteLine("Year " + year + 1 +" In Charge");
Console.WriteLine("The city population is now " + people);
Console.WriteLine("The city owns " + land + " acres");
Console.WriteLine("You now have " + food + " bushels in store.");
Console.WriteLine("Land is trading at " + landprice + " bushels per acre.");
Console.WriteLine();
Console.Write("How Many Acres Would You Like To Buy? ");
landin = int.Parse(Console.ReadLine());
Console.WriteLine();
food = food - landprice * landin;
land = landin + land;
if (landin * landprice <= food)
{
Console.WriteLine("You Bought " + landin + " Acres");
Console.WriteLine("You Own " + land + " Acres");
Console.WriteLine("You Have " + food + " Bushell Left");
Console.WriteLine();
}
else if (landin * landprice > food)
{
Console.WriteLine("You Dont Have Enought Bushell ");
return;
}
Console.Write("How Many Acres Would You Like To Sell? ");
landout = int.Parse(Console.ReadLine());
Console.WriteLine();
land = land - landout;
food = landprice * landout + food;
if (landout <= land)
{
Console.WriteLine("You Sold " + landout + " Acres");
Console.WriteLine("You Own " + land + " Acres");
Console.WriteLine("You Now Have " + food + " Bushells");
Console.WriteLine();
}
else if (landout > land)
{
Console.WriteLine("You Dont Own Enough Acres - Please Reset");
return;
}
Console.Write("How Many Bushell Would You Like To Feed Your People? ");
foodin = int.Parse(Console.ReadLine());
Console.WriteLine();
totalfoodcost = people * foodcost;
if (foodin == totalfoodcost && foodin < food)
{
Console.WriteLine("Your People Have Eaten");
food = food - totalfoodcost;
Console.WriteLine("You Have " + food + " Bushell Left");
Console.WriteLine();
}
else if (foodin > food)
{
Console.WriteLine("You Dont Have Enought Bushell - Please Restart! ");
return;
}
else if (foodin < totalfoodcost)
{
Console.WriteLine("You Have Been Over Thrown As People Are Hungry - Please Restart! ");
return;
}
Console.Write("How Many Acres Do You Wish To Plant With Seed? ");
seeds = int.Parse(Console.ReadLine());
Console.WriteLine();
if (seeds <= food && seeds <= people)
{
Console.WriteLine("You Have Planted " + seeds + " Seeds");
food = food - seeds;
Console.WriteLine("You Now Have " + food + " Bushell");
Console.WriteLine();
}
else if (seeds > food)
{
Console.WriteLine("You Do Not Have Enought Bushell");
}
else if (seeds > people)
{
Console.WriteLine("You Do Not Have Enought People");
}
Console.WriteLine("End Of Year " + year);
}
}
}
First of all, you need to divide your program into functions as per its duty (Seperation of Concerns)
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int land = 1000, people = 100, landprice = rnd.Next(17, 26);
int foodin = 0, landin = 0, landout = 0, seeds = 0;
int foodcost = 20, food = 2800, totalfoodcost = 0;
int year = 0;
for (; year < <break_condition> ; year++)
StartMyGame(land, foodin, foodcost, year);
}
}
furthermore, you can also use goto statement
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int land = 1000, people = 100, landprice = rnd.Next(17, 26);
int foodin = 0, landin = 0, landout = 0, seeds = 0;
int foodcost = 20, food = 2800, totalfoodcost = 0;
int year = 0;
game_start_pos:
StartMyGame(land, foodin, foodcost, year++);
if (!<your_break_condition> )
goto game_start_pos:
}
}
This is my code I resolved it by, I used a while loop.
using System;
namespace Game2
{
class Program
{
static void Main(string[] args)
{
{
// This is the to allow random numbers to be created
Random rand = new Random(DateTime.Now.Millisecond);
Random ran1 = new Random(DateTime.Now.Millisecond);
Random ran2 = new Random(DateTime.Now.Millisecond);
Random ran3 = new Random(DateTime.Now.Millisecond);
Random ran4 = new Random(DateTime.Now.Millisecond);
//this is my integer which will hold my data
int people = 100, landPrice = 0;
int foodIn = 000, landIn = 0000, landOut = 0000, seeds = 0;
int foodCost = 20, food = 2800, totalFoodCost = 0000;
int year = 1;
int land = 1000;
int newPeople = 0;
int peopleDied = 0;
int seedCost = 0;
int rats = 0;
int peopleSell = 0;
double landFinal = 0;
peopleSell = people * 10;
//game rules and start of game
Console.WriteLine("Game Rules! ");
Console.WriteLine("The game lasts 10 years, with a year being one turn. ");
Console.WriteLine("Each year, enter how many bushels of grain to allocate to buying (or selling) acres of land, feeding your population, and planting crops for the next year ");
Console.WriteLine("Each person needs 20 bushels of grain each year to live and can till at most 10 acres of land. ");
Console.WriteLine("Each acre of land requires one bushel of grain to plant seeds. ");
Console.WriteLine("The price of each acre of land fluctuates from 17 bushels per acre to 26 bushels. ");
Console.WriteLine("If the conditions in your country ever become bad enough, the people will overthrow you and you won't finish your 10 year term. ");
Console.WriteLine("If you make it to the 11th year, your rule will be evaluated ");
Console.WriteLine();
Console.WriteLine("TRY YOUR HAND AT GOVERNING ANCIENT SUMERIA");
Console.WriteLine("SUCCESSFULLY FOR A 10 YEAR TERM OF OFFICE.");
Console.WriteLine();
Console.WriteLine("HAMURABI: I BEG TO REPORT TO YOU,");
Console.WriteLine();
// loop to add + 1 to year if year is <= 10 and people > 0
while (year <= 10 && people > 0)
{
// this will random gen a number between 17 and 26
landPrice = rand.Next(17, 26);
Console.WriteLine("Year " + year + " In Charge.");
Console.WriteLine();
Console.WriteLine("You Harvested " + seeds + " Bushels.");
Console.WriteLine(newPeople + " People Came To The City.");
Console.WriteLine(peopleDied + " Died In The City.");
Console.WriteLine("Rats Have Eaten " + rats + " Bushels.");
people = people + newPeople;
people = people - peopleDied;
Console.WriteLine("The City's Population Is Now " + people + ".");
Console.WriteLine("The City Owns " + land + " Acres.");
food = seeds + food;
food = food - rats;
Console.WriteLine("You Now Have " + food + " Bushels In Storage.");
Console.WriteLine("Land is trading at " + landPrice + " Bushels per Acre.");
Console.WriteLine();
landFinal = ((double)land / people);
//start of game
// Section for user to enter how many acres would like to buy
Console.Write("How Many Acres Would You Like To Buy? ");
landIn = int.Parse(Console.ReadLine());
Console.WriteLine();
// this will random gen a number between 1 and 10 and 0 and 5 and so on.
newPeople = ran1.Next(1, 10);
peopleDied = ran2.Next(0, 5);
rats = ran3.Next(50, 500);
// loop if landIn * landPrice > food or landIn < 0 will show error and ask user to input again
while (landIn * landPrice > food || landIn < 0)
{
Console.WriteLine("You Dont Have Enough Bushels!! ");
Console.Write("PLEASE RE ENTER: How Many Acres Would You Like To Buy? ");
landIn = int.Parse(Console.ReadLine());
Console.WriteLine();
}
// loop if landIn * landPrice < food then allows user to go on and shows summary
if (landIn * landPrice < food)
{
food = food - landPrice * landIn;
land = landIn + land;
Console.WriteLine("You Bought " + landIn + " Acres.");
Console.WriteLine("You Own " + land + " Acres.");
Console.WriteLine("You Have " + food + " Bushels Left.");
Console.WriteLine();
}
// Section for user to enter how many acres would like to sell
Console.Write("How Many Acres Would You Like To Sell? ");
landOut = int.Parse(Console.ReadLine());
// loop if land < landOut or landIn < 0 will show error and ask user to input again
Console.WriteLine();
while (land < landOut || landOut < 0)
{
Console.WriteLine("You Dont Own Enough Acres!!");
Console.Write("RE ENTER How Many Acres Would You Like To Sell? ");
landOut = int.Parse(Console.ReadLine());
Console.WriteLine();
}
//if the loop condition is met will allow user to carry on.
if (landOut < land || landOut == land)
land = land - landOut;
food = food + landPrice * landOut;
{
Console.WriteLine("You Sold " + landOut + " Acres.");
Console.WriteLine("You Own " + land + " Acres.");
Console.WriteLine("You Now Have " + food + " Bushels.");
Console.WriteLine();
}
// Section for user to enter how many bushel to feed their people.
Console.Write("How Many Bushels Would You Like To Feed Your People? ");
foodIn = int.Parse(Console.ReadLine());
Console.WriteLine();
// Section if condition not met user will have to re enter value
while (foodIn > food || foodIn < 0)
{
Console.WriteLine("You Dont Have Enough Bushels!!");
Console.Write("RE ENTER How Many Bushels Would You Like To Feed Your People? ");
foodIn = int.Parse(Console.ReadLine());
Console.WriteLine();
}
totalFoodCost = people * foodCost;
// if condition met user can carry on
if (foodIn >= totalFoodCost && foodIn <= food)
{
Console.WriteLine("Your People Have Eaten.");
Console.WriteLine();
food = food - foodIn;
Console.WriteLine("You Have " + food + " Bushels Left.");
Console.WriteLine();
}
// Section if condition not met user will have to re enter values
else if (foodIn < totalFoodCost)
{
Console.WriteLine("You Have Been Over Thrown As People Are Hungry - Please Restart! ");
return;
}
Console.Write("How Many Acres Do You Wish To Plant With Seed? ");
seeds = int.Parse(Console.ReadLine());
Console.WriteLine();
seedCost = (people * 10);
while (seeds > seedCost || seeds < 0)
{
Console.WriteLine("You Dont Have Enough People! ");
Console.Write("How Many Acres Do You Wish To Plant With Seed? ");
seeds = int.Parse(Console.ReadLine());
Console.WriteLine();
}
if (seeds < seedCost && seeds < food)
{
Console.WriteLine("You Have Planted " + seeds + " Seeds.");
food = food - seeds;
Console.WriteLine("You Now Have " + food + " Bushels.");
Console.WriteLine();
}
while (land == 1 || seeds > land || seeds < 0)
{
Console.WriteLine("You Dont Have Enough Land!!");
Console.Write("How Many Acres Do You Wish To Plant With Seed? ");
seeds = int.Parse(Console.ReadLine());
Console.WriteLine();
}
while (seeds > food || seeds < 0)
{
Console.WriteLine("You Dont Have Enough Bushels!!");
Console.Write("How Many Acres Do You Wish To Plant With Seed? ");
seeds = int.Parse(Console.ReadLine());
Console.WriteLine();
}
food = food - seeds;
seeds = seeds * rand.Next(2, 8);
//end of year summary will loop untill year 11.
Console.WriteLine("End Of Year " + year + ".");
year = year + 1;
Console.WriteLine();
Console.WriteLine("You Ended With " + food + " Bushels.");
Console.WriteLine("You Ended With " + land + " Acres.");
Console.WriteLine();
landFinal = ((double)land / people);
// end of year final summary
if (year == 11)
{
Console.WriteLine("Congratulations On Reaching The End Of Your Term!");
Console.WriteLine();
Console.WriteLine("You Ended With " + food + " Bushels.");
Console.WriteLine("You Ended With " + land + " Acres.");
Console.WriteLine("You Ended With " + people + " People.");
Console.WriteLine("Each Person Ended With " + landFinal + " Per Acre.");
Console.WriteLine();
landFinal = ((double)land / people);
}
//failed year summary
if (year == 11 && landFinal < 10)
{
Console.WriteLine("You Have Been Marked As A Failure For Your Service!!");
return;
}
//sucessful game summary
if (year == 11 && landFinal >= 10)
{
Console.WriteLine("You Are A Great King!!");
return;
}
}
}
}
}
}
Related
Why does not while loop stop?
int Coins = 27; int playersInput =0; int counter = 0; while (Coins >= 0) { Console.WriteLine("There are " + (Coins - playersInput) + " in the bag" + "\n"); Console.WriteLine("Turn #" + (counter + 1)); playersInput += Convert.ToInt32(Console.ReadLine()); if (playersInput % 2 == 0) { Console.WriteLine("Player 0 turn"); } else { Console.WriteLine("Player 1 turn"); } counter++; } Console.WriteLine("The last player lost this game"); The code has to alternate between two players and if the coins value reaches to 0 it has to print the console.writeline that is outside the while loop and I don't want to use break.
You never update Coins and the number of coins left in the jar is Coins - playersInput. while ((Coins - playersInput) >= 0)
Problem with withdraw and balance, calculation is not working correctly on the second try
Problem: If you deposit 1000-->then borrow 40000-->then withdraw 43000 and get the error "insufficient balance" --> then try again and deposit 28000. The issue here is that the balance is -31000 the second time you try instead of something around 12000. Anyone that knows why? I've tried moving the capital "statement" into the else statement but that just made things worse. I've also tried moving it to the account stats section but that didn't work either. I'm new to this and im not really that good at problem solving so sorry if it's something obvious:/ using System; namespace atmtest { class Program { public static void Main() { int balance = 0, deposit = 0, withdraw = 0, choice, loan = 0, kredit = 0, debt = 0, capital = 0; while (true) { Console.WriteLine("----------------------------"); Console.WriteLine("Welcome"); Console.WriteLine("----------------------------"); Console.WriteLine("1) Deposit"); Console.WriteLine("2) Withdraw"); Console.WriteLine("3) Account stats"); Console.WriteLine("4) Borrow money"); Console.WriteLine("--------------------------------"); Console.WriteLine("Enter one of the options "); choice = int.Parse(Console.ReadLine()); switch (choice) { case 1: Console.Clear(); try { Console.WriteLine("Deposit, enter amount : "); deposit = int.Parse(Console.ReadLine()); if (deposit > 500000) { Console.WriteLine("Error, max amount 500000"); } else if (deposit < 0) { Console.WriteLine("Error, the amount has to be positive"); } else { capital = balance + deposit; Console.WriteLine("You have deposited " + deposit + " and your balance is now: " + capital); } } catch { Console.WriteLine("Error, enter numbers only."); } break; case 2: Console.Clear(); Console.WriteLine("Withdraw, enter amount: "); withdraw = int.Parse(Console.ReadLine()); capital = kredit + balance - withdraw; balance = balance - withdraw; if ((withdraw > balance) && (withdraw > kredit)) { Console.WriteLine("Error, insufficent balance."); capital = deposit; Console.WriteLine("Try again"); } else { debt = balance; Console.WriteLine("You have withdrawn " + withdraw); Console.WriteLine("Your current balance is " + capital); } break; case 3: Console.Clear(); Console.WriteLine("Account stats: "); Console.WriteLine("Balance: " + capital); Console.WriteLine("Amount of money borrowed ( loan ): " + kredit); Console.WriteLine("Debt: " + debt); Console.WriteLine("You have used " + debt ); break; case 4: Console.Clear(); Console.WriteLine("how much do you want to borrow? Max amount is 50000."); Console.WriteLine("Enter amount: "); loan = int.Parse(Console.ReadLine()); kredit = loan + kredit; if (kredit > 50000) { Console.WriteLine("You cannot borrow this amount, max amount is 50000"); kredit = kredit - loan; } else if (kredit <= 50000) { Console.WriteLine("You have been granted " + loan); } break; } } } } }
Try this little change to track your variable values, actually the message you are getting is correct. These are based on your values assignment only. Please change the snippet and try to run : int balance = 0, deposit = 0, withdraw = 0, choice, loan = 0, kredit = 0, debt = 0, capital = 0; StringBuilder audit = new StringBuilder(); while (true) { Console.WriteLine("----------------------------"); Console.WriteLine("Welcome"); Console.WriteLine("----------------------------"); Console.WriteLine("Audit"); audit.Append($" balance = {balance}, deposit = {deposit}, withdraw = {withdraw}, loan = {loan}, kredit = {kredit}, debt = {debt}, capital = {capital} \n"); Console.WriteLine(audit.ToString()); Console.WriteLine("----------------------------"); Console.WriteLine("1) Deposit"); Console.WriteLine("2) Withdraw"); Console.WriteLine("3) Account stats"); Console.WriteLine("4) Borrow money"); Console.WriteLine("--------------------------------"); Console.WriteLine("Enter one of the options "); .... .... Here is the picture It is clearly showing after withdraw balance not reduced, hence need programmatic correction in logic.
I just run the code. You are constantly mixing different terms like capital and balance. Try to use only one of the variables in your code. In addition, since you are new, it is a good habit to extract lines of code to methods to make everything more structured and better readable. This is quite important for bigger applications. Something like this in a new class file: public class BankingConsole { private int Balance { get; set; } = 0; private int Deposit { get; set; } = 0; private int Withdraw { get; set; } = 0; private int Loan { get; set; } = 0; private int Credit { get; set; } = 0; private int Debt { get; set; } = 0; private int Choice { get; set; } = 0; public BankingConsole() { StartSimulation(); } public void StartSimulation() { while (true) { Console.WriteLine("Balance: " + Balance.ToString()); Console.WriteLine("----------------------------"); Console.WriteLine("Welcome"); Console.WriteLine("----------------------------"); Console.WriteLine("1) Deposit"); Console.WriteLine("2) Withdraw"); Console.WriteLine("3) Account stats"); Console.WriteLine("4) Borrow money"); Console.WriteLine("--------------------------------"); Console.WriteLine("Enter one of the options "); Choice = int.Parse(Console.ReadLine()); Console.Clear(); switch (Choice) { case 1: DepositMoney(); break; case 2: WithdrawMoney(); break; case 3: ShowAccountStats(); break; case 4: BorrowMoney(); break; default: break; } } } private void DepositMoney() { try { Console.WriteLine("Deposit, enter amount : "); Deposit = int.Parse(Console.ReadLine()); if (Deposit > 500000) { Console.WriteLine("Error, max amount 500000"); } else if (Deposit < 0) { Console.WriteLine("Error, the amount has to be positive"); } else { Balance += Deposit; Console.WriteLine("You have deposited " + Deposit + " and your balance is now: " + Balance); } } catch { Console.WriteLine("Error, enter numbers only."); } } private void WithdrawMoney() { Console.WriteLine("Withdraw, enter amount: "); Withdraw = int.Parse(Console.ReadLine()); if (Withdraw > Balance) { Console.WriteLine("Error, insufficent funds."); } else { Balance -= Withdraw; Debt += Withdraw; Console.WriteLine("You have withdrawn " + Withdraw); Console.WriteLine("Your current balance is " + Balance); } } private void ShowAccountStats() { Console.WriteLine("Account stats: "); Console.WriteLine("Balance: " + Balance); Console.WriteLine("Amount of money borrowed ( loan ): " + Credit); Console.WriteLine("Debt: " + Debt); } private void BorrowMoney() { Console.WriteLine("how much do you want to borrow? Max amount is 50000."); Console.WriteLine("Enter amount: "); Loan = int.Parse(Console.ReadLine()); if (Credit + Loan > 50000) { Console.WriteLine("You cannot borrow this amount, max amount is 50000"); } else { Credit += Loan; Balance += Loan; Console.WriteLine("You have been granted " + Loan); } } } And you call this code in your main like this: static void Main(string[] args) { new BankingConsole().StartSimulation(); }
using System; namespace atmtest { class Program { static void Main(string[] args) { int balance = 0, deposit = 0, withdraw = 0, choice, loan = 0, kredit = 0, debt = 0, capital = 0, repay = 0; while (true) { Console.WriteLine("----------------------------"); Console.WriteLine("Welcome"); Console.WriteLine("----------------------------"); Console.WriteLine("1) Deposit"); Console.WriteLine("2) Withdraw"); Console.WriteLine("3) Account stats"); Console.WriteLine("4) Borrow money"); Console.WriteLine("5) Return borrowed money"); Console.WriteLine("--------------------------------"); Console.WriteLine("Enter one of the options "); choice = int.Parse(Console.ReadLine()); switch (choice) { case 1: Console.Clear(); try { Console.WriteLine("Deposit, enter amount : "); deposit = int.Parse(Console.ReadLine()); if (deposit > 500000) { Console.WriteLine("Error, max amount 500000"); } else if (deposit < 0) { Console.WriteLine("Error, the deposit has to be positive."); } else { balance = balance + deposit; Console.WriteLine($"You have deposited {deposit} and your balance is now: {balance}."); } } catch { Console.WriteLine("Error, enter numbers only."); } break; case 2: Console.Clear(); try { Console.WriteLine("Withdraw, enter amount: "); withdraw = int.Parse(Console.ReadLine()); if (withdraw < 0) { Console.WriteLine("The amount must be positive number."); } else if (withdraw > balance) { Console.WriteLine($"Error, insufficent balance {balance}.\nTry again."); } else { balance = balance - withdraw; Console.WriteLine($"You have withdrawn {withdraw}. Your current balance is {balance}."); } } catch { Console.WriteLine("Error. Enter numbers only."); } break; case 3: Console.Clear(); Console.WriteLine("Account stats: "); Console.WriteLine("Balance: " + balance); Console.WriteLine("Debt: " + debt); break; case 4: Console.Clear(); try { Console.WriteLine("how much do you want to borrow? Max amount is 50000."); Console.WriteLine("Enter amount: "); loan = int.Parse(Console.ReadLine()); if (loan < 0) { Console.WriteLine("Loan cannot be negative."); } else if (loan > 50000) { Console.WriteLine("You cannot borrow this amount, max amount is 50000"); } else if (debt + loan > 50000) { Console.WriteLine( $"You cannot borrow this amount it makes your debt {debt + loan} > max debt amount 50000."); } else { debt += loan; balance += loan; Console.WriteLine($"You borrowed {loan} and your kredit now is {kredit}."); } } catch { Console.WriteLine("Error. Enter numbers only."); } break; case 5: Console.Clear(); try { Console.WriteLine("how much do you want to repay? Max amount is 50000."); Console.WriteLine("Enter amount: "); repay = int.Parse(Console.ReadLine()); int maxRepay = (debt < 50000) ? debt : 50000; if (repay < 0) { Console.WriteLine($"You cannot repay negative amount {repay}"); } else if (repay > maxRepay) { Console.WriteLine($"Repay cannot be more than {maxRepay}."); } else { debt -= repay; balance -= repay; Console.WriteLine($"You repaied {repay} of the debt. You debt now is {debt}."); } } catch { Console.WriteLine("Error. Enter numbers only."); } break; } } } } }
I changed a few code from the original code, and I noticed that on your switch statement case 2, even there is withdraw > balance, your program will still makes balance -= withdraw first because the balance = balance - withdraw is coded outside of the if statement and that will produce your error. using System; namespace simpleAtm { class Program { static void Main() { int balance = 0, deposit = 0, withdraw = 0, choice, loan = 0, kredit = 0, debt = 0, capital = 0; while (true) { Console.WriteLine("----------------------------"); Console.WriteLine("Welcome"); Console.WriteLine("----------------------------"); Console.WriteLine("1) Deposit"); Console.WriteLine("2) Withdraw"); Console.WriteLine("3) Account stats"); Console.WriteLine("4) Borrow money"); Console.WriteLine("--------------------------------"); Console.WriteLine("Enter one of the options "); choice = int.Parse(Console.ReadLine()); switch (choice) { case 1: Console.Clear(); try { Console.WriteLine("Deposit, enter amount : "); deposit = int.Parse(Console.ReadLine()); if (deposit > 500000) { Console.WriteLine("Error, max amount 500000"); } else if (deposit < 0) { Console.WriteLine("Error, the amount has to be positive"); } else { capital += balance + deposit; Console.WriteLine("You have deposited " + deposit + " and your balance is now: " + capital); } } catch { Console.WriteLine("Error, enter numbers only."); } break; case 2: Console.Clear(); balance = capital; Console.WriteLine(capital); Console.WriteLine("Withdraw, enter amount: "); withdraw = int.Parse(Console.ReadLine()); if (withdraw > balance + kredit) { Console.WriteLine("Error, insufficent balance."); capital = deposit; Console.WriteLine("Try again"); } else { balance -= withdraw; if(balance - withdraw < 0){ balance *= -1; kredit -= balance; balance = 0; capital = kredit; Console.WriteLine(balance+" "+kredit); debt += withdraw; Console.WriteLine("You have withdrawn " + withdraw); Console.WriteLine("Your current balance is " + capital); } else{ capital = balance + kredit; debt += withdraw; Console.WriteLine("You have withdrawn " + withdraw); Console.WriteLine("Your current balance is " + capital); } } break; case 3: Console.Clear(); Console.WriteLine("Account stats: "); Console.WriteLine("Balance: " + capital); Console.WriteLine("Amount of money borrowed ( loan ): " + kredit); Console.WriteLine("Debt: " + debt); Console.WriteLine("You have used " + debt ); break; case 4: Console.Clear(); Console.WriteLine("how much do you want to borrow? Max amount is 50000."); Console.WriteLine("Enter amount: "); loan = int.Parse(Console.ReadLine()); kredit = loan + kredit; if (kredit > 50000) { Console.WriteLine("You cannot borrow this amount, max amount is 50000"); kredit = kredit - loan; } else if (kredit <= 50000) { Console.WriteLine("You have been granted " + loan); } break; } } } } }
Sum up all numbers between two numbers
I am a beginner in C# programming and trying to code a method that ask the user to give a start and an end integer number, then sum up all numbers from the start to the end and in case the given start number is greater than the end number, swap the values so that the start number becomes the end number and the end number gets the value of the start number. This what I have done so far but I'm not getting the right answer when running the app: private void SumNumbers() { int startNumber, endNumber; Console.WriteLine("\nplease enter a start number: "); startNumber = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("\nplease enter an end number: "); endNumber = Convert.ToInt32(Console.ReadLine()); int result = 0; for (int i=0; i<=startNumber; i=i+1) { result = result + i; Console.WriteLine(i); } Console.ReadLine(); Console.WriteLine("The sum of Numbers between " + startNumber + " and " + endNumber + " is: " + result.ToString()); Console.ReadLine(); } I'm getting this result: The sum of Numbers between 12 and 23 is: 78 when the result actually need to 210.
for (int i=0;i<=startNumber;i=i+1) You are iterating from 0 to startNumber, when really you want to iterate like startNumber to endNumber. Try for (int i = startNumber; i <= endNumber; i = i+1)
Below is the working example. I also added some logic to handle the checking of the input (whether it is correct or no) so the application doesn't break. This way the user experience is much better. Here is the live working example: code private void SumNumbers() { int startNumber, endNumber; Console.WriteLine("\nplease enter a start number: "); do { var input1 = Console.ReadLine(); if (Regex.IsMatch(input1, #"^\d+$")) { startNumber = Convert.ToInt32(input1); break; } else { Console.WriteLine("Input provided is invalid. Please enter a correct number: "); } } while (true); Console.WriteLine("\nplease enter an end number: "); do { var input2 = Console.ReadLine(); if (Regex.IsMatch(input2, #"^\d+$")) { endNumber = Convert.ToInt32(input2); break; } else { Console.WriteLine("Input provided is invalid. Please enter a correct number: "); } } while (true); int min = Math.Min(startNumber, endNumber); int max = Math.Max(startNumber, endNumber); int result = 0; for (int i = min; i <= max; i++) { result = result + i; Console.WriteLine(i); } Console.WriteLine("The sum of Numbers between " + min + " and " + max + " is: " + result.ToString()); Console.ReadLine(); }
Number Guessing Game in c#
I'm working on Visual Studio about binary search in c#. My project about the computer find the user's guess number. So, I use tihs code in the main; int min = 0; // minimum number in the array int max = 100; // maximum number in the array int middle = 50; // middle number in the array int counter = 1; string name, input; int guess_number; Console.WriteLine("Hello, this is a game that finding the number of in your mind. If you want to play so let me know you! "); name = Console.ReadLine(); Console.WriteLine("Awesome welcome to the game " + name + " guess a number between " + min + " and " + max + " Please! "); Console.WriteLine("Is your guess " + middle + " ?\nIf it's your guess then write (0) please!\nIf it's too high then write (1) please!\nIf it's too low then write (2) please!"); input = Console.ReadLine(); guess_number = Convert.ToInt32(input); Console.WriteLine(" You select " + guess_number + " so, "); do { counter += 1; if (guess_number == 2) { min = middle + 1; } else if (guess_number == 1) { max = middle - 1; } else if (guess_number != 1 || guess_number != 2 || guess_number != 0) { Console.WriteLine(" Please write 0, 1 or 2 " + name); } middle = (min + max) / 2; Console.WriteLine("Is your guess " + middle + " ?\nIf it's your guess then write (0) please!\nIf it's too high then write (1) please!\nIf it's too low then write (2) please!"); Console.WriteLine(counter + " times I tried for finding your number "); } while (guess_number != 0); Console.ReadKey(); However, output always repeat after the user write anything, why the reason about that, is there anyway to get the number?
from your description, I think you need to let user input new value to guess_number variable in the loop end otherwise the loop will not end from the condition guess_number != 0. do { counter += 1; if (guess_number == 2) { min = middle + 1; } else if (guess_number == 1) { max = middle - 1; } else if (guess_number != 1 || guess_number != 2 || guess_number != 0) { Console.WriteLine(" Please write 0, 1 or 2 " + name); } middle = (min + max) / 2; Console.WriteLine("Is your guess " + middle + " ?\nIf it's your guess then write (0) please!\nIf it's too high then write (1) please!\nIf it's too low then write (2) please!"); Console.WriteLine(counter + " times I tried for finding your number "); input = Console.ReadLine(); // let user key in new value. guess_number = Convert.ToInt32(input); } while (guess_number != 0);
the last readKey should be inside the while. do { counter += 1; if (guess_number == 2) { min = middle + 1; } else if (guess_number == 1) { max = middle - 1; } else if (guess_number != 1 || guess_number != 2 || guess_number != 0) { Console.WriteLine(" Please write 0, 1 or 2 " + name); } middle = (min + max) / 2; Console.WriteLine("Is your guess " + middle + " ?\nIf it's your guess then write (0) please!\nIf it's too high then write (1) please!\nIf it's too low then write (2) please!"); input = Console.ReadLine(); guess_number = Convert.ToInt32(input); Console.WriteLine(counter + " times I tried for finding your number "); } while (guess_number != 0);
Basic C# Dice Game
I am new to c# and coding in general. To try and improve my skills I am trying to create a basic game where two players roll a dice and keep record of their score. The player wins by reaching 20. Each player takes turns rolling a dice adding their first roll to their second and so on until one of them reaches 20. A player can roll the dice again if they roll a six. The current code I have is: do { Console.Write("Enter the name of Player 1: "); Player[0] = Console.ReadLine(); Console.Write("Enter the name of Player 2: "); Player[1] = Console.ReadLine(); Random DiceRandom = new Random(); DiceThrow[0] = DiceRandom.Next(1, 7); int i = 0; while (i <= 1) { DiceThrow[0 + i] = DiceRandom.Next(1, 7); Console.ReadLine(); Console.Write(Player[0 + i] + " rolled a " + DiceThrow[0 + i]); if (DiceThrow[0 + i] != 6) i++; } Console.ReadLine(); PlayerTotal[0] = DiceThrow[0]; PlayerTotal[1] = DiceThrow[1]; Console.ReadLine(); Console.Write(Player[0] + " currently has " + PlayerTotal[0]); Console.ReadLine(); Console.Write(Player[1] + " currently has " + PlayerTotal[1]); Console.ReadLine(); } while (PlayerTotal[0] == 20); while (PlayerTotal[1] == 20); What I am specifically struggling with is adding the players first roll to there second roll. And if a player rolls a six that it adds the 6 to what they get in the re-roll. Any help at all will be greatly appreciated.
There are a number of concerns with your code here: you are asking the player name inside the loop You are initializing the Random generator inside the loop (this can cause same results on different loops because the random generator can use the same seed) You are resetting totals using = instead of += The stop condition is totals == 20 instead of total < 20 you are using two while statement instead of an AND (&&) condition This is just a brief overview.. This can be a solution: Console.Write("Enter the name of Player 1: "); Player[0] = Console.ReadLine(); Console.Write("Enter the name of Player 2: "); Player[1] = Console.ReadLine(); Random DiceRandom = new Random(); do { int i = 0; while (i <= 1) { int thisThrow = DiceRandom.Next(1, 6); DiceThrow[0 + i] += thisThrow; Console.ReadLine(); Console.Write(Player[0 + i] + " rolled a " + thisThrow); if (thisThrow != 6) i++; } Console.ReadLine(); PlayerTotal[0] += DiceThrow[0]; PlayerTotal[1] += DiceThrow[1]; Console.ReadLine(); Console.Write(Player[0] + " currently has " + PlayerTotal[0]); Console.ReadLine(); Console.Write(Player[1] + " currently has " + PlayerTotal[1]); Console.ReadLine(); } while (PlayerTotal[0] < 20 && PlayerTotal[1] < 20);
Your problem is that you're reseting the previous scores with these lines: PlayerTotal[0] = DiceThrow[0]; PlayerTotal[1] = DiceThrow[1]; You should change it to use += like this: PlayerTotal[0] += DiceThrow[0]; PlayerTotal[1] += DiceThrow[1]; Which is like saying: PlayerTotal[0] = PlayerTotal[0] + DiceThrow[0]; Other then that, there are a few more problems in your code. For instance, you have one Do at the beginning of the code but 2 whiles... You probably want to create one While with an AND statement. Also, the Do statement needs to be after you get the user's names... For instance: // Get User names do { // All your Dice throwing logic } while (PlayerTotal[0] != 20 && PlayerTotal[1] != 20);
int i = 0; while (i <= 1) { int thisThrow = DiceRandom.Next(1, 6); DiceThrow[0 + i] += thisThrow; Console.ReadLine(); Console.Write(Player[0 + i] + " rolled a " + thisThrow); if (thisThrow != 6) i++; } Console.ReadLine(); PlayerTotal[0] += DiceThrow[0]; PlayerTotal[1] += DiceThrow[1]; Console.ReadLine(); Console.Write(Player[0] + " currently has " + PlayerTotal[0]); Console.ReadLine(); Console.Write(Player[1] + " currently has " + PlayerTotal[1]); Console.ReadLine();