How to get out of a while-loop in c# - c#

Here I am trying to have the user enter "YES" to continue with the game but i'm stuck in the while-loop. This is also my first post so I don't the correct way to post ie. copy and paste? Also is there a indentation shortcut for Visual Studio? Thanks for helping.
using System;
namespace BIT_142_Major_Assignment_1
{
class Program
{
static void Main(string[] args)
{
int numGames = 0;
String answer = "";
Random rand = new Random();
int Dice1 = rand.Next(1, 7);
int Dice2 = rand.Next(1, 7);
Console.WriteLine("Hey! Welcome to Andy’s Dice Game.");
Console.WriteLine("Let’s start!");
{
while (true)
{
numGames++;
Console.WriteLine("Dice 1: " + Dice1);
Console.WriteLine("Dice 2: " + Dice2);
Console.WriteLine("I got " + Dice1 + " and " + Dice2 + "!");
if ((Dice1 + Dice2) % 2 == 0)
{
Console.WriteLine("Evens are better than odds!");
}
else
{
Console.WriteLine("Odds are still cool!");
Console.WriteLine("Do you want to play again?");
answer = Console.ReadLine();
if (answer == "YES")
{
continue;
}
else
{
Console.WriteLine("The number of times the dice was thrown is: " + numGames);
Console.WriteLine("Nice Game!");
Console.WriteLine("Thank for playing, Come play again soon!");
break;
}
}
}
}
}
}
}

Related

method endgame() cannot be called

So for the main class, I only have this code. Calling the cClass. THIS IS A DICE GAME
{
class Program
{
static void Main(string[] args)
{
cClass cs = new cClass();
}
}
For the Constructor class, which is cClass i have this code. The method endgame() is not working. This is where the problem located the when the dice game done battling, the endgame() is not working.
class cClass
{
public cClass()
{
Intialize();
}
public void Intialize()
{
sClass.round = 1;
while (sClass.com < 3 && sClass.player < 3)
{
start:
Console.WriteLine("Round (" + sClass.round + ")");
Console.WriteLine("Enter your guess: ( 1 - 6)");
sClass.guess = Convert.ToInt32(Console.ReadLine());
if (sClass.guess >= 7)
{
Console.WriteLine("Only enter number ranges from 1 - 6");
Console.ReadLine();
Console.Clear();
goto start;
}
sClass.playgame();
System.Threading.Thread.Sleep(1000);
Console.WriteLine("\nThe dice rolled is...");
Console.WriteLine(sClass.playerdie);
Console.WriteLine("\nPlayer guessed: " + sClass.guess);
Console.WriteLine("Computer guessed: " + sClass.comguess);
if ((sClass.comguess == sClass.playerdie) && (sClass.guess == sClass.playerdie))
{
Console.WriteLine("\nBoth guessed correctly! Restarting the round!\n");
Console.WriteLine("Player points: " + sClass.player);
Console.WriteLine("Computer points: " + sClass.com);
}
else if (sClass.guess == sClass.playerdie)
{
sClass.player++;
Console.WriteLine("\nPlayer guessed correctly you won!\n");
Console.WriteLine("Player points: " + sClass.player);
Console.WriteLine("Computer points: " + sClass.com);
sClass.round++;
}
else if (sClass.comguess == sClass.playerdie)
{
sClass.com++;
Console.WriteLine("\nComputer guessed correctly you lost...\n");
Console.WriteLine("Player points: " + sClass.player);
Console.WriteLine("Computer points: " + sClass.com);
sClass.round++;
}
else
{
Console.WriteLine("\nNo one got it correct restarting the round!\n");
Console.WriteLine("Player points: " + sClass.player);
Console.WriteLine("Computer points: " + sClass.com);
}
Console.ReadLine();
Console.Clear();
}
endgame();
}
public void endgame()
{
if (sClass.player > sClass.com)
{
Console.WriteLine("Player Win! Player vs Computer");
Console.WriteLine(" (" + sClass.player + ") vs (" + sClass.com + ")");
}
else if (sClass.player < sClass.com)
{
Console.WriteLine("Computer Win! Player vs Computer");
Console.WriteLine(" (" + sClass.player + ") vs (" + sClass.com + ")");
}
else
{
Console.WriteLine("Its a draw! Player vs Computer");
Console.WriteLine(" (" + sClass.player + ") vs (" + sClass.com + ")");
}
}
}
then I also have a static class , which is sClass.
static class sClass
{
public static int dice = 1;
public static int playerdie;
public static int guess;
public static int comguess;
public static int player;
public static int com;
public static int round;
public static Random r = new Random();
public static void playgame()
{
comguess = r.Next(1, 6);
playerdie = rolldie();
}
public static int rolldie()
{
int die = r.Next(1, 6);
return die;
}
}
So, you just said that there is no error. I think you just missed only 1 code. In cClass.cs Go to the Initialize() method, go at the endgame() then put the Console.ReadLine above the endgame
endgame();
Console.ReadLine();
Then it will show the endgame method.
Currently, your while loop says that it's checking on both simultaniously:
while (sClass.com < 3 && sClass.player < 3)
I said formerly if it should be an OR-statement, but that didn't work, because then either of them would still be true, continue-ing the while loop.
So it'll only stop the while loop if all statements are false.
Perhaps this code will work:
while (!(sClass.com >= 3 && sClass.player >= 3))
What I did now is reversing the while check, and now it checks if both are still false, and the ! will reverse that false to true. So if either of the scores becomes 3 now, it'll go out of the while loop.

I dont press enter but ReadLine() says I did (accidently made it that you cant answer the old one so repost)

Fixed, but now it automatically presses enter when it gets to the Main(); thing and I can't actually input anything in time. Anyone know what's wrong?
using System;
using System.Linq;
namespace Bruh
{
class Program
{
static void Main()
{
int pog = 0;
int pog2 = 0;
Random r = new Random();
Console.WriteLine("Input a whole number");
string poggers = Console.ReadLine();
if (int.TryParse(poggers, out pog))
{
pog = int.Parse(poggers);
}
else
{
Console.WriteLine("ERROR: Not a number. Please input a number and not letters.");
Console.Read();
System.Environment.Exit(1);
}
Console.WriteLine("Input a number higher than the previous");
string poggers2 = Console.ReadLine();
if (int.TryParse(poggers2, out pog2))
{
pog2 = int.Parse(poggers2);
}
else
{
Console.WriteLine("ERROR: Not a number. Please input a number and not letters.");
Console.Read();
System.Environment.Exit(1);
}
int genRand = r.Next(pog, pog2);
Console.WriteLine("This number was randomly generated between " + pog + " and " + pog2 + " and we got: " + genRand);
Console.Read();
Console.WriteLine("Would you like to try again? Y/N");
ConsoleKeyInfo answer = Console.ReadKey();
if (answer.KeyChar == 'y' || answer.KeyChar == 'Y')
{
Console.WriteLine("\n");
Main();
}
else if (answer.KeyChar == 'n' || answer.KeyChar == 'N')
{
System.Environment.Exit(1);
}
else
{
Console.WriteLine("ERROR: Y/N not any other character");
Console.Read();
System.Environment.Exit(1);
}
}
}
}
I've reworked your code into something that is more C#-like :-) - find this below.
Highlights:
You use int.TryParse() correctly, but do the conversion again
inside the true code block, using int.Parse().
No need to call System.Environment.Exit(1); to terminate the program, just let it end.
The call main() is actually a recursive call - where a method (function) calls it self. Usable sometimes, but i often leads to a StackOverflow exception. In this case, you get some strange behaviour...
using System;
namespace Bruh2
{
class Program
{
static void Main()
{
bool tryAgain = true;
while (tryAgain)
{
int pog = 0;
int pog2 = 0;
Random r = new Random();
Console.Write("Input a whole number: ");
string poggers = Console.ReadLine();
while (!int.TryParse(poggers, out pog))
{
Console.WriteLine("ERROR: Not a number. Please input a number and not letters.");
poggers = Console.ReadLine();
}
Console.Write("Input a number higher than the previous: ");
string poggers2 = Console.ReadLine();
while (!int.TryParse(poggers2, out pog2))
{
Console.WriteLine("ERROR: Not a number. Please input a number and not letters.");
poggers2 = Console.ReadLine();
}
int genRand = r.Next(pog, pog2);
Console.WriteLine("This number was randomly generated between " + pog + " and " + pog2 + " and we got: " + genRand);
Console.WriteLine();
Console.WriteLine("Would you like to try again? Y/N");
//ConsoleKeyInfo answer = Console.ReadKey();
string answer = Console.ReadKey().KeyChar.ToString().ToLower();
while (answer!="y" && answer!="n")
{
Console.WriteLine("ERROR: Y/N not any other character");
answer = Console.ReadKey().ToString().ToLower();
}
if (answer == "n")
{
tryAgain = false; // terminate the loop (and thereby the program)
}
}
}
}
}

Program won't move onto next method

My program won't move onto the next method after it executes the main method.
Right now, it just prints out "Hey! Welcome to Tina's Dice Game. Let's Start!", and then stops. How do I fix this? I've messed around with it for a while, but nothing worked. Thank you for your help.
using System;
namespace Major_Coding_Assignment_1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hey! Welcome to Tina's Dice Game.");
Console.WriteLine("Let's start!");
}
public static int numberofInvokes = 0;
public void EvenOrOdd()
{
numberofInvokes += 1;
Random rnd = new Random();
int x = rnd.Next(1, 7);
int y = rnd.Next(1, 7);
int added = x + y;
if (added % 2 == 0)
{
Console.WriteLine("I got" + " " + x + " " + "and" + " " + y);
Console.WriteLine("Evens are better than odds.");
}
else
{
Console.WriteLine("I got" + " " + x + " " + "and" + " " + y);
Console.WriteLine("Odds are still cool!");
}
}
public void playAgain()
{
Console.WriteLine("Do you want to play again?");
string val = Console.ReadLine();
if (val == "yes")
{
EvenOrOdd();
}
else
{
Console.WriteLine("The number of times the dice was thrown is:" + " " + numberofInvokes);
Console.WriteLine("Thanks for playing, come play again soon!");
}
}
}
}
You need to call the methods you need from the main function like this...
static void Main(string[] args)
{
Console.WriteLine("Hey! Welcome to Tina's Dice Game.");
Console.WriteLine("Let's start!");
EvenOrOdd();
playAgain();
}
The better way is to call playAgain inside EvenOrOdd method to make things look cleaner.
static void Main(string[] args)
{
Console.WriteLine("Hey! Welcome to Tina's Dice Game.");
Console.WriteLine("Let's start!");
EvenOrOdd();
}
public static int numberofInvokes = 0;
public void EvenOrOdd()
{
numberofInvokes += 1;
Random rnd = new Random();
int x = rnd.Next(1, 7);
int y = rnd.Next(1, 7);
int added = x + y;
if (added % 2 == 0)
{
Console.WriteLine("I got" + " " + x + " " + "and" + " " + y);
Console.WriteLine("Evens are better than odds.");
}
else
{
Console.WriteLine("I got" + " " + x + " " + "and" + " " + y);
Console.WriteLine("Odds are still cool!");
}
playAgain(); //Call playAgain from here.
}
public void playAgain()
{
Console.WriteLine("Do you want to play again?");
string val = Console.ReadLine();
if (val == "yes")
{
EvenOrOdd();
}
else
{
Console.WriteLine("The number of times the dice was thrown is:" + " " + numberofInvokes);
Console.WriteLine("Thanks for playing, come play again soon!");
}
}
its important that you call your methods from main. I like to think of it like a recipe main is the first instruction but you need to tell the reader where to look next. The same is true for C#, you need to tell the compiler where to go next by calling the next function in the main one.
static void Main(string[] args)
{
//your start code
nextFunction();
}
public void nextFunction(){
//your next function code
}

1. How can I get my random number to be different each time it is printed out? 2. Are there any basic things that I can improve upon? [duplicate]

This question already has answers here:
Random number generator only generating one random number
(15 answers)
Closed 4 years ago.
I am very new to programming as a whole and C# is my first language. I have been working on this project for the past few weeks or so that gives the user 3 options of whether they want to use a random number generator, calculator or roll a dice.
So far everything is going okay. I have been focusing quite a lot on exception handling and commenting to make sure that everything is as clear as possible. One problem that I have come across and am not surer how to fix is that in my dice rolling procedure it prints out the same random dice number x times rather than printing out different random numbers each time. So if you could help me fix that that would be awesome. Here is just the code for that;
static void rollDice()
{
Boolean rollAgain = false;
while (rollAgain == false)
{
Console.Write("Enter the number of sides on your dice: "); //Need to do exception handling for this
int totalSides = int.Parse(Console.ReadLine());
Console.WriteLine("How many times would you like to roll the {0} sided dice?", totalSides); //Need to do exception handling for this
int numRolls = int.Parse(Console.ReadLine());
for (int i = 0; i < numRolls; i++)
{
Random rnd = new Random();
int diceNumber = rnd.Next(1, totalSides);
Console.Write("\t" + diceNumber);
}
Console.WriteLine("\nIf you like to roll a dice with a different number of sides enter Y\nTo exit the application enter N");
string doRerun = Console.ReadLine();
if (doRerun == "Y" || doRerun == "y")
{
rollAgain = false;
}
else if (doRerun == "N" || doRerun == "n")
{
rollAgain = true;
}
}
}
Also, as I'm a newbie in general, I think some feedback from more experienced users will benefit me as a whole. Is there any mistakes I've made> Any informal rules I have broken? Please let me know I will be very thankful. Here is all of the code;
static void Main(string[] args)
{
Boolean chooseRun = false;
while (chooseRun == false)
{
Console.WriteLine("To use the calculator enter C\nTo use the random number generator enter R\nTo roll a dice enter D");
string chooseProc = Console.ReadLine();
if (chooseProc == "C" || chooseProc == "c")
{
calculator();
chooseRun = true;
}
else if (chooseProc == "R" || chooseProc == "r")
{
numGenerator();
chooseRun = true;
}
else if (chooseProc == "D" || chooseProc == "d")
{
rollDice();
chooseRun = true;
}
else
{
Console.WriteLine("Sorry that was an invalid input. Please try again");
chooseRun = false;
}
}
Console.Write("Goodbye");
Console.ReadKey();
}
/// <summary>
/// Here I have a simple calculator that can do basic functions such as subtraction and then I give them the option to use it again
/// </summary>
static void calculator()
{
int loop = 1;
while (loop == 1)
{
Console.WriteLine("You chose to use the calculator!\nPress the enter key to start"); //Greet the user and give them the option of when they want to start the calculator based upon when they choose to click the enter key
Console.ReadKey(true);
int num1 = 0; //Declaring variables
int num2 = 0;
string operation = "";
int answer;
Boolean gotnum1 = false;
while (gotnum1 == false)
{
Console.Write("Enter the first number in your equation: "); //Then I give them a message to greet them and give them the option of when to start the calculator
try
{
num1 = int.Parse(Console.ReadLine());
gotnum1 = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Boolean gotnum2 = false;
while (gotnum2 == false)
{
Console.Write("Enter the second number in your equation: "); //Then I give them a message to greet them and give them the option of when to start the calculator
try
{
num2 = int.Parse(Console.ReadLine());
gotnum2 = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Boolean gotOpr = false;
while (gotOpr == false)
{
Console.Write("Ok now enter your operation ( x , / , +, -) ");
operation = Console.ReadLine();
switch (operation)
{
case "x":
answer = num1 * num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
break;
case "X":
answer = num1 * num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
break;
case "/":
try
{
answer = num1 / num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
}
catch (DivideByZeroException e)
{
Console.WriteLine("You cannot divide by zero");
}
break;
case "+":
answer = num1 + num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
break;
case "-":
answer = num1 - num2;
Console.WriteLine(num1 + " " + operation + " " + num2 + " = " + answer);
gotOpr = true;
break;
default:
Console.WriteLine("Sorry that is an invalid input");
gotOpr = false;
break;
}
}
Console.WriteLine("Do you want to use the calculator again? Select;\nIf you would please enter /Y/\nIf not please enter /N/");
string rerun = Console.ReadLine();
if (rerun.ToUpper() == "N")
{
loop = 0;
}
}
}
/// <summary>
/// This procedure generates a random number and gives the user the option as to whether they would like to generate another
/// </summary>
static void numGenerator()
{
Console.WriteLine("You chose to use the random number generator");
Boolean moreNum = false;
while (moreNum == false)
{
Random r = new Random();
int n = r.Next();
Console.WriteLine(n);
Console.WriteLine("If you would like another number enter Y, otherwise please enter N");
string rerun = Console.ReadLine();
if (rerun == "Y" || rerun == "y")
{
moreNum = false;
}
else if (rerun == "N" || rerun =="n")
{
moreNum = true;
}
}
}
/// <summary>
/// In this procedure a virtual dice is rolled of a user inputted number of times, this too gives the user the option to roll the dice again after rolling it x times
/// </summary>
static void rollDice()
{
Boolean rollAgain = false;
while (rollAgain == false)
{
Console.Write("Enter the number of sides on your dice: "); //Need to do exception handling for this
int totalSides = int.Parse(Console.ReadLine());
Console.WriteLine("How many times would you like to roll the {0} sided dice?", totalSides); //Need to do exception handling for this
int numRolls = int.Parse(Console.ReadLine());
for (int i = 0; i < numRolls; i++)
{
Random rnd = new Random();
int diceNumber = rnd.Next(1, totalSides);
Console.Write("\t" + diceNumber);
}
Console.WriteLine("\nIf you like to roll a dice with a different number of sides enter Y\nTo exit the application enter N");
string doRerun = Console.ReadLine();
if (doRerun == "Y" || doRerun == "y")
{
rollAgain = false;
}
else if (doRerun == "N" || doRerun == "n")
{
rollAgain = true;
}
}
}
You should create the Random object only once, typically create is in a static field (if you create it many times, it would generate the same values every time)
static Random rnd = new Random();

How to start over with my code? C# Console [duplicate]

This question already has answers here:
How to loop a Console App
(6 answers)
Closed 6 years ago.
I wanted to try how the if conditional works so I created this code almost by myself. I also had problems with random into int.
Here's my code:
using System;
namespace Bigger_Smaller_Equal
{
class Program
{
static void Main(string[] args)
{
int min = 1;
int max = 100;
Random rnd = new Random();
int gen = rnd.Next(min, max);
Console.WriteLine("My Number is : " + gen + "!");
Console.WriteLine("Tell me your number:");
string typ = Console.ReadLine();
int num = int.Parse(typ);
if (num == gen)
{
Console.WriteLine(num + " is Equal to " + gen);
}
else if (num > gen)
{
Console.WriteLine(num + " Is Bigger than " + gen);
}
else if (num < gen)
{
Console.WriteLine(num + " Is Smaller than " + gen);
}
Console.WriteLine("Press Any Key to exit.");
Console.ReadLine();
}
}
}
How to make the console stop, so it will allow me to enter another number?
Basically:
I write a number it tells me if its smaller bigger or equal to number which was randomly generated
After I press enter instead of closing the console the number will be generated again and I can write new number and so on.
Here's an example using goto, although it is not recommended for more complex applications as you could end up creating endless loops. Feel free to try it out
static void Main(string[] args)
{
int min = 1;
int max = 100;
Random rnd = new Random();
again:
int gen = rnd.Next(min, max);
Console.WriteLine("My Number is : " + gen + "!");
Console.WriteLine("Tell me your number:");
string typ = Console.ReadLine();
int num = int.Parse(typ);
if (num == gen)
{
Console.WriteLine(num + " is Equal to " + gen);
}
else if (num > gen)
{
Console.WriteLine(num + " Is Bigger than " + gen);
}
else if (num < gen)
{
Console.WriteLine(num + " Is Smaller than " + gen);
}
repeat:
Console.WriteLine("Play again? (Y/N)");
string ans = Console.ReadLine();
switch (ans.ToUpper())
{
case "Y": goto again; break;
case "N": break; //continue
default: goto repeat; break;
}
}
You can use console.ReadKey() insted of using console.ReadLine().
console.ReadLine() wait for input set of character thats why you console window is apperre there after pressing any key.
You can use "do while" or "while" operator.If you dont want to use while(true) , you can use this diffirent way. I mean that when user enter 0 or -1 this system can stop. while()
bool repeat = true;
do
{
Console.WriteLine("Enter value ");
string typ = Console.ReadLine();
int num = int.Parse(typ);
if (num!=0)
// bla bla bla.
else
repeat = false;
}while (repeat);

Categories