I am very new to code. Can anyone in a simple way explain why I cant use the goto statement like this, to make the code start over again? Or, how this could have been done in the correct way? And also, why I get an error message on the use of "static".
**
"No such label "Start" within the scope of the goto statmenet"
"The modifier static is not valid for this item"
using System;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
Start:
Random numberGenerator = new Random();
int num1 = numberGenerator.Next(1,11);
int num2 = numberGenerator.Next(1, 4);
Console.WriteLine("What is " + num1 + " times " + num2 + "?");
int svar = Convert.ToInt32(Console.ReadLine());
if (svar == num1 * num2)
{
Console.WriteLine("well done!");
}
else
{
int responseIndex = numberGenerator.Next(1, 4);
switch (responseIndex)
{
case 1:
Console.WriteLine("Wrong, try again? [Y or N]");
AskUser();
break;
case 2:
Console.WriteLine("The answer was incorrect");
AskUser();
break;
default:
Console.WriteLine("You can do better than that");
AskUser();
break;
}
static void AskUser() {
string jaellernei = Console.ReadLine().ToUpper();
if (jaellernei == "Y")
{
goto Start;
} else
{
return;
} }
}
}
}
}
Firstly, your AskUser method is incorrectly nested inside the other method - move it out.
Secondly: goto is only valid within a single method; you can jump around a single stack frame - you cannot jump between stack frames.
Thirdly: the number of times you should be using goto... well, it isn't quite zero, but it asymptotically approaches zero.
Don't use goto unless you MUST to !
and As #Marc Gravell said, it's valid within a single method.
Alternatively : you can make a method of the code u used in the Main method, and then call it from both, main method and the other method where you used goto statement.
Like :
using System;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
someFunction();
}
static void someFunction()
{
Random numberGenerator = new Random();
int num1 = numberGenerator.Next(1, 11);
int num2 = numberGenerator.Next(1, 4);
Console.WriteLine("What is " + num1 + " times " + num2 + "?");
int svar = Convert.ToInt32(Console.ReadLine());
if (svar == num1 * num2)
{
Console.WriteLine("well done!");
}
else
{
int responseIndex = numberGenerator.Next(1, 4);
switch (responseIndex)
{
case 1:
Console.WriteLine("Wrong, try again? [Y or N]");
AskUser();
break;
case 2:
Console.WriteLine("The answer was incorrect");
AskUser();
break;
default:
Console.WriteLine("You can do better than that");
AskUser();
break;
}
}
}
static void AskUser()
{
string jaellernei = Console.ReadLine().ToUpper();
if (jaellernei == "Y")
{
someFunction();
}
else
{
return;
}
}
}
}
You could do it like this
public static Random randd = new Random();
public static void FlachCards()
{
Start:
if (AskAUser() == "Y")
{
goto Start;
}
}
public static String AskAUser()
{
Console.WriteLine("Enter Y to play again");
return Console.ReadLine();
}
Related
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)
}
}
}
}
}
I have created a console application where the user has 5 tries to guess number between 1 and 100. After 5 guesses the game ends, but I don’t know how to introduce at the 5th wrong intent something like “you have achieved maximum of guesses! The answer was number (X). I have tried different ways ,but is not working. This is my program
using System;
namespace Guessing_Game_4
{
class Program
{
static void Main(string[] args)
{
var number = new Random().Next(1, 100);
Console.WriteLine("Try and guess any number between 1-100. You have 5 guesses Max!");
for (var i = 0; i < 5; i++)
{
int guess = Convert.ToInt32(Console.ReadLine());
if (guess == number)
{
Console.WriteLine("You got it!");
break;
}
else
{
Console.WriteLine(guess + " is not correct! Try again!");
}
}
}
}
}
Here some Sample code
This might help
for( i=10;i>0 ; i--) {
System.out.println(" === you have " + i +" Guesses left ===");
int guess = scanner.nextInt();
if (random_number < guess) System.out.println("Smaller than guess " + guess);
if (random_number > guess) System.out.println("Greater than guess " + guess);
if (random_number == guess)
{
result = true;
break;
}
}
if (result)
{
System.out.println("You WON in "+(10-i) +" tries ");
System.out.println("******* CONGRATULATIONS **************************************");
System.out.println("*********************** YOU WON **********************");
}
else
{
System.out.println("The random number was "+random_number);
System.out.println("************************** OPPS You loose **************************************** ");
System.out.println("You are near it TRY Next time ************ GOOD LUCK ");
System.out.println("You are near it TRY Nexttime***********NEXTTIME********");
}
}
If that's all your program does, you can do the following trick. Print your message after the for loop, but now the problem is that you get the message in all cases. The trick is to return from the Main (instead of breaking the loop) on a correct guess:
Console.WriteLine("You got it!");
return;
If you've some other code to execute that returning from Main won't be a good solution, you can do the following:
Create a variable before the for loop. Let's call it isCorrectAnswer and set it to false in the beginning.
At the point where he answers correctly, set isCorrectAnswer to true before breaking the loop.
After the loop, check for that variable:
if (!isCorrectAnswer)
{
Console.WriteLine($"you have achieved maximum of guesses! The answer was number {number}.");
}
You have to have an int outside of your loop like this : int wrongAnswersCount = 0;
When the user enter a wrong number you
should add one unit to your variable wrongAnswersCount++;
In the start of the loop, you should check if the user reached the maximum amount of gueses or not, if yes break the loop and say the answer.
Your code will be something like this :
using System;
namespace Guessing_Game_4
{
class Program
{
static void Main(string[] args)
{
var number = new Random().Next(1, 100);
Console.WriteLine("Try and guess any number between 1-100. You have 5 guesses Max!");
int wrongAnswersCount = 0;
for (var i = 0; i < 5; i++)
{
if(wrongAnswersCount == 5)
{
Console.WriteLine($"you have achieved maximum of guesses! The answer was number {number}");
break;
}
int guess = Convert.ToInt32(Console.ReadLine());
if (guess == number)
{
Console.WriteLine("You got it!");
break;
}
else
{
Console.WriteLine(guess + " is not correct! Try again!");
wrongAnswersCount++;
}
}
}
}
}
class Program
{
static void Main(string[] args)
{
var number = new Random().Next(1, 100);
Console.WriteLine("Try and guess any number between 1-100. You have 5 guesses Max!");
for (var i = 0; i < 5; i++)
{
int guess = Convert.ToInt32(Console.ReadLine());
if (guess == number && i!=5)
{
Console.WriteLine("You got it!");
break;
}
else
{
Console.WriteLine(guess + " is not correct! Try again!");
}
}
Console.WriteLine(" the maximam guse");
}
}
//Try this one
I'm having issues creating a program that is a number guessing program. I think I have the written part right but possibly not the order of it? I have to use multiple methods such as a method for number generator of the number that is supposed to be guessed, a method for collecting the guess input, and method for checking the guess to see if it's right. I've literally have tried just about everything for days but all I get is rather a repeat of, "Enter the number: " even if its right, although it's supposed to repeat if it's too high or low. Or sometimes the console won't print anything. what is wrong? Here is the code:
using System;
namespace GuessTheNumber
{
class Program
{
public static int RandomNumberGenerator()
{
Random random = new Random();
return random.Next(1, 21);
}
public static int InputGetter()
{
Console.Write("Enter in a number: ");
int guess = Convert.ToInt32(Console.ReadLine());
return guess;
}
public static String GuessChecker(int guess, int secretNumber)
{
if(guess > secretNumber)
{
return "Too high!";
}
else if (guess < secretNumber)
{
return "Too low!";
}
else
{
return "Correct";
}
}
static void Main(string[] args)
{
int secretNumber = 10;
Console.WriteLine("" + secretNumber);
while (true)
{
while (InputGetter() != secretNumber)
{
InputGetter();
GuessChecker(InputGetter(), secretNumber);
}
if (GuessChecker(InputGetter(), secretNumber) == ("Correct!"))
{
Console.WriteLine("Would you like to play again?");
String input = Console.ReadLine();
if (GuessChecker(InputGetter(), secretNumber) == ("Yes"))
{
secretNumber = RandomNumberGenerator();
}
else if (GuessChecker(InputGetter(), secretNumber) == ("No"))
{
break;
}
}
}
}
}
}
You are invoking InputGetter() multiple times and your logic is incorrect.
It has nothing to do with Random instance being used.
I have quickly modified your code and it should work now as follows:
New number is generated, if you enter low/high message is displayed, if you enter correct number you are presented with the Would you like to try again message.
EDIT: I did not want to change original code much,In general Comparing strings is bad, you should not use it. Creating enum like and comparing would be much better
class Program
{
public static int RandomNumberGenerator()
{
Random random = new Random();
var generatedNumber = random.Next(1, 21);
Console.WriteLine($"New Number generated! {generatedNumber}");
return generatedNumber;
}
public static int InputGetter()
{
Console.Write("Enter in a number: ");
int guess = Convert.ToInt32(Console.ReadLine());
return guess;
}
public static String GuessChecker(int guess, int secretNumber)
{
if (guess > secretNumber)
{
Console.WriteLine("Too High");
return "Too high!";
}
else if (guess < secretNumber)
{
Console.WriteLine("Too low!");
return "Too low!";
}
else
{
Console.WriteLine("Correct");
return "Correct";
}
}
static void Main(string[] args)
{
int secretNumber = 10;
Console.WriteLine("" + secretNumber);
while (true)
{
int enteredNumber = 0;
do
{
enteredNumber = InputGetter();
} while (GuessChecker(enteredNumber, secretNumber)!="Correct");
Console.WriteLine("Would you like to play again?[Yes/No]");
String input = Console.ReadLine();
if (input=="Yes")
{
secretNumber = RandomNumberGenerator();
}
else
{
break;
}
}
}
}
I'm new to c# and am trying to make a simple calculator.
It works fine until it goes back to the start to take a new number.
When taking the new number it says it cant convert the user input to a integer.
using System;
namespace simpleCalculator
{
class MainClass
{
public static void Main(string[] args)
{
start:
Console.Clear();
Console.WriteLine("Enter first number");
int x = Convert.ToConsole.ReadLine();
Console.WriteLine("Would you like to\n1. Add\n2. Multiply\n3. Devide");
string o = Console.ReadLine();
if (o == "1")
{
Console.WriteLine("Enter second number\n");
int y = Convert.ToInt32(Console.ReadLine());
add(temp, y);
goto start;
Console.Clear();
goto start;
}
}
public static void add(int num01, int num02)
{
Console.Clear();
Console.WriteLine((num01 + num02) + "\nPress enter to contiue.");
Console.Read();
}
}
}
Use TryParse so if the parsing fails, you will not get an exception.
var enteredValue = Console.ReadLine();
var parsedValue;
if (!int.TryParse(enteredValue, out parsedValue))
{
// parse failed do whatever you want
}
Do that for both entries and if both of them pass, then call your add method.
You're looking for int.Parse(). Be careful to validate your input. You should probably create an escape condition.
Edited to show an alternative solution
Edited to be more explicit on how to handle some input
class Program
{
public static void Main(string[] args)
{
string input = String.Empty;
int x = 0, y = 0;
while (true)
{
try
{
Console.WriteLine("Enter first number");
x = int.Parse(Console.ReadLine());
Console.WriteLine("Would you like to\n1. Add\n2. Multiply\n3. Divide");
input = Console.ReadLine();
Console.WriteLine("Please enter a second number");
y = int.Parse(Console.ReadLine());
}
catch
{
Console.WriteLine("Invalid input");
continue;
}
switch (input)
{
case "1":
Console.WriteLine($"{x} + {y} = " + add(x, y));
break;
case "2":
//TODO implement multiply case
break;
case "3":
//TODO implement divide case
break;
default:
Console.WriteLine("Invalid input");
break;
}
}
}
public static int add(int x, int y) => x + y;
}
Try this:
int numbers = Convert.ToInt32("1234");
pretty new to programming and I'm a bit stuck. This is the first program I've written with two classes (in two seperate class files). I'll include all the code below. It's a program to play a dice game called Craps. My task is too create a method in the CrapsGame class that allows me to play the game over and over again until I decide to stop. But I'm having a little trouble working out how to correctly call the manyPlay() method. I'm not really sure what I'm doing. The program will play the game once by calling myCraps.play() but then won't go any further. If anyone else notices anything wrong with the code or anything that's bad practice then please point it out as I am very keen to learn. Thanks to anyone that takes the time to answer.
using System;
namespace Task4_7
{
public class CrapsGame
{
string replay;
private Craps myCraps;
private CrapsGame newGame;
public static void Main()
{
CrapsGame newGame = new CrapsGame();
Craps myCraps = new Craps ();
myCraps.play ();
newGame.manyPlay ();
}
public void manyPlay() {
string input; // declare local variable
do {
myCraps.play();
replay:
Console.Write("Would you like to play again? y/n");
input = Console.ReadLine();
if (input == "y") {
replay = input;
}
else if (input == "n") {
replay = "n";
}
else {
Console.WriteLine("\n Erroneous input. Please enter y (yes) or n (no)");
goto replay;
}
}
while(replay != "n");
}
}
}
using System;
namespace Task4_7
{
public class Craps
{
private Random randy; // define randy as a Random class
public Craps() {
this.randy = new Random ();
}
public int oneThrow() {
return randy.Next(6) + 1; // pick a number from 1 to 6 and return this
}
public int throw2Dice() {
int a, b, c;
a = oneThrow ();
b = oneThrow ();
c = a + b;
Console.WriteLine ("You threw a " + a + " and a " + b + " making " + c);
return c;
}
public void play() {
int result = throw2Dice ();
switch (result) {
case 2:
Console.WriteLine ("You lose! End of game!");
break;
case 3:
Console.WriteLine ("You lose! End of game!");
break;
case 12:
Console.WriteLine ("You lose! End of game!");
break;
case 7:
Console.WriteLine ("You win! End of game!");
break;
case 11:
Console.WriteLine ("You win! End of game!");
break;
case 4:
Console.WriteLine ("Your point! Rolling again!");
throwPoint (result);
break;
case 5:
Console.WriteLine ("Your point! Rolling again!");
throwPoint (result);
break;
case 6:
Console.WriteLine ("Your point! Rolling again!");
throwPoint (result);
break;
case 8:
Console.WriteLine ("Your point! Rolling again!");
throwPoint (result);
break;
case 9:
Console.WriteLine ("Your point! Rolling again!");
throwPoint (result);
break;
default:
Console.WriteLine ("Your point! Rolling again!");
throwPoint (result);
break;
}
}
public void throwPoint(int result) {
Throw:
int a = throw2Dice();
if (a == result) {
Console.WriteLine ("You rolled the same score! You win!");
} else if (a == 7) {
Console.WriteLine ("You rolled a 7! You loose!");
} else {
Console.WriteLine ("You rolled a " + a + ". Rolling again!");
goto Throw;
}
}
}
}
This is your problem:
Craps myCraps = new Craps();
You are hiding variable of class CrapsGame with a local variable of Main method. Simply change it to
myCraps = new Craps();
and it should work.
EDIT
and change myCraps declaration to static, of course.
EDIT2
Scope of variables: C# variable scoping not consistent?
My first suggestion is put your Main method in a seperate file.For example you can use three files: Program.cs, CrapsGame.cs, Craps.cs. To do this just add a new class file,and move your main method to new Class file. Second, never use goto.Instead use while loop like this,
public void throwPoint(int result) {
while(true)
{
int a = throw2Dice();
if (a == result) {
Console.WriteLine ("You rolled the same score! You win!");
break;
} else if (a == 7) {
Console.WriteLine ("You rolled a 7! You loose!");
break;
} else {
Console.WriteLine ("You rolled a " + a + ". Rolling again!");
}
}
}
Many play method:
public void manyPlay() {
string input; // declare local variable
myCraps.play();
while(true) {
Console.Write("Would you like to play again? y/n");
input = Console.ReadLine();
if (input == "y") {
myCraps.play();
}
else if (input == "n") {
break;
}
else {
Console.WriteLine("\n Erroneous input. Please enter y (yes) or n (no)");
}
}
}
The problem looks like you where creating a game for use by the game iterator, but it needs to create a game for each iteration. So I delete some code: all the class variables have to go, variables should be as local as possible.
using System;
namespace Task4_7
{
public class CrapsGame
{
public static void Main()
{
new Craps ().play ();
new CrapsGame().manyPlay ();
}
public void manyPlay() {
string replay;
string input; // declare local variable
do {
new Craps().play();
replay:
Console.Write("Would you like to play again? y/n");
input = Console.ReadLine();
if (input == "y") {
replay = input;
}
else if (input == "n") {
replay = "n";
}
else {
Console.WriteLine("\n Erroneous input. Please enter y (yes) or n (no)");
goto replay;
}
}
while(replay != "n");
}
}
}
Now fix that loop: no gotos. You need a loop in a loop, as you have but don't build your own loops.
Then if Craps.play() returned a score. You could add a class variable to accumulate the score.
Change replay to boolean and make set it to true if input is y and false if input is n.
Then change your main method.
public static void Main()
{
CrapsGame newGame = new CrapsGame();
Craps myCraps = new Craps ();
while (replay == true) {
myCraps.play ();
newGame.manyPlay ();
}
}