Random Number generator fail - c#

How do I get the program to loop back around from the beginning if the incorrect number is picked? I'm not sure what I'm doing wrong. I tried ifs, do whiles, whiles, and if elses:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArrayProblms
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Guess a number between 1 and 10: ");
RandomNumberGenerator();
Console.ReadLine();
}
public static void RandomNumberGenerator()
{
Random rand = new Random();
int userValue = int.Parse(Console.ReadLine());
int randValue = rand.Next(1, 11);
int attempts = 0;
if (userValue == randValue)
{
Console.WriteLine("You have guessed correctly!");
}
while (userValue != randValue)
{
Console.WriteLine("You have guessed incorrectly");
attempts++;
Console.WriteLine("You have made {0} incorrect guesses", attempts);
break;
}
}
}
}

You should put int userValue = int.Parse(Console.ReadLine()); inside the loop and check input on every iteration. break must be only if userValue == randValue:
public static void RandomNumberGenerator()
{
Random rand = new Random();
int randValue = rand.Next(1, 11);
int attempts = 0;
while (true)
{
int userValue = int.Parse(Console.ReadLine()); // input inside the loop
if (userValue == randValue) // checking inside the loop
{
Console.WriteLine("You have guessed correctly!");
break;
}
Console.WriteLine("You have guessed incorrectly");
attempts++;
Console.WriteLine("You have made {0} incorrect guesses", attempts);
}
}

I would use do...while to continue asking user to enter the new number until he guessed correctly.
Example below:
public static void RandomNumberGenerator()
{
Random rand = new Random();
int randValue = rand.Next(1, 11);
int attempts = 0;
// do...while cycle to ask user to enter new value each time the used has been wrong
do
{
// read user input
int userValue = int.Parse(Console.ReadLine());
// if user guessed correct
if (userValue == randValue)
{
Console.WriteLine("You have guessed correctly!");
// go away from do...while loop
// it will stop asking user and will exit from the method
break;
}
// if user has been wrong
Console.WriteLine("You have guessed incorrectly");
// increment attempts count
attempts++;
Console.WriteLine("You have made {0} incorrect guesses", attempts);
}
// and repeat until user guessed correctly
while(userValue != randValue)
}

You're on the right track, but you need to put the Console.ReadLine inside a while loop and break out of the loop only when the user's value matches.
Something like this pseudo code:
Generate random number
while (true) {
Get value from user
If it matches, break
}

Related

I am new here as well as into coding ! I solved a problem but i was wondering if the same problem could be solved in different/shorter ways?

The Problem:
Imagine you are a developer and get a job in which you need to create a program for a teacher. He needs a program written in c# that calculates the average score of his students. So he wants to be able to enter each score individually and then get the final average score once he enters -1.
So the tool should check if the entry is a number and should add that to the sum. Finally once he is done entering scores, the program should write onto the console what the average score is.
The numbers entered should only be between 0 and 20. Make sure the program doesn't crash if the teacher enters an incorrect value.
Test your program thoroughly.
My solution to the problem :
static void Main(string[] args)
{
int digit = 0,sum=0,counter=0;
string x;
try
{
for (int i = 0; i <= counter; i++)
{
Console.WriteLine("Please Enter Score");
x = Console.ReadLine();
bool isParsable = Int32.TryParse(x,out digit);
if (isParsable)
{
if (digit >= 0 && digit <= 20)
{
Console.WriteLine("Valid Number");
sum += digit;
counter++;
Console.WriteLine($"Student number {counter} got {digit}");
}
else if (digit == -1)
{
Console.WriteLine($"Total sum is {sum}");
Console.WriteLine($"Total number of students is {counter}");
Console.WriteLine($"Average score of {counter} students is {sum / counter}");
break;
}
else
{
Console.WriteLine("Please enter a valid score");
}
}
Console.WriteLine("Please enter Numerical Values only");
}
}
catch (DivideByZeroException)
{
Console.WriteLine("Unable to get results");
}
}

Number guessing game using TryParse

I´m having problems with getting my code to work while using TryParse to catch if the user where to input a string instead of a int. If I use it as it looks now I only get the base value of 0 if something other than an int is input. I want it to show an error message to the user.
Have tried messing around with a number of different ways of using TryParse but none of them has really been helpfull.
static void Main(string[] args)
{
Random r = new Random();
int speltal = r.Next(1,21);
bool play = false;
int myNum;
while (!play)
{
Console.Write("\n\tGuess a number between 1 and 20: ");
Int32.TryParse(Console.ReadLine(), out myNum);
if (myNum < guessNum)
{
Console.WriteLine("\tThe number you have guessed is to low");
Console.ReadLine();
}
if (myNum > guessNum)
{
Console.WriteLine("\tThe number you have guessed is to high");
Console.ReadLine();
}
if (myNum == guessNum)
{
Console.WriteLine("\tCongratulations you guessed the right number!");
Console.ReadLine();
}
I want it show an error message to the user if they put in anything other than a int. It also have to include TryParse according to my teatcher
You're not capturing the bool output of TryParse so you have no idea if a non-numeric value was entered. Try something like this:
bool isValid;
do
{
Console.Write("\n\tGuess a number between 1 and 20: ");
isValid = Int32.TryParse(Console.ReadLine(), out myNum);
if(!isValid)
{
Console.WriteLine("\n\tInvalid input detected. Please try again.");
}
} while(!isValid)
The TryParse method can only put integers in the passed variable (as it is of type int), so if the value passed to it can't be parsed into an integer, the default value of int (0) will be assigned to the variable.
The way TryParse tell you if it successfully parsed the number or not, is by returning a boolean indicator.
You can try this:
while (true)
{
bool valid = int.TryParse(Console.ReadLine(), out myNum);
if(valid)
break;
Console.WriteLine("Input invalid. Please try again");
}
TryParse returns a Boolean which indicates if the input string was successfully parsed or not. Both of the answers above are correct on how to handle a invalid input but, here is a cleaner version which will also uphold the rule, between 1 and 20:
while (true)
{
Console.Write("\n\tGuess a number between 1 and 20: ");
//Checks to see if the input was successfully parsed to a integer also, performs a Trim on the input as to remove any accidental white spaces that a user might have typed in, e.g. "1000 "
if (int.TryParse(Console.ReadLine().Trim(), out myNum))
{
//Checks to see if the parsed number is in the specified range
if ((myNum > 0) && (myNum < 21))
{
break;
}
Console.WriteLine("\tThe input number was out of the specified range.");
}
else
{
Console.WriteLine("\tFailed to parse the input text.");
}
//Optional, makes the thread sleep so the user has the time to read the error message.
Thread.Sleep(1500);
//Optional, clears the console as to not create duplicates of the error message and the value of Console.Write
Console.Clear();
}
// Continue here, if (myNum < guessNum) . . .
You should use the bool returned by TryParse. Something that looks like this:
Updated answer:
static void Main(string[] args)
{
Random random = new Random();
int guessNum = random.Next(1, 21);
while(true)
{
Console.WriteLine("Guess the number between 1 and 21.");
if (Int32.TryParse(Console.ReadLine(), out int input))
{
if (input == guessNum)
{
Console.WriteLine($"You guessed it right. The number is {input}");
if(ShouldContinue())
{
guessNum = random.Next();
continue;
}
else
{
break;
}
}
if (input < guessNum)
Console.WriteLine("The number you guessed is smaller.");
else
Console.WriteLine("The number you guessed is bigger");
}
else
{
Console.WriteLine("Please enter a number between 1 and 21 as your guess");
}
}
}
static bool ShouldContinue()
{
while (true)
{
Console.WriteLine($"Do you want to continue playing? (y/n)");
string continueInput = Console.ReadLine().Trim().ToLower();
if (continueInput == "y")
return true;
else if (continueInput == "n")
return false;
else
Console.WriteLine("Invalid input!. Please choose 'y' or 'n'.");
}
}
Old answer:
while (true)
{
if (Int32.TryParse(inputInt, out int myNum))
{
// your logic goes here, too low/high or correct answer.
}
}

How to assign a value read from the console to an integer field?

In my hangman game, I am attempting to prompt the user to enter the number of "lives" (or guesses) the player should be given. After I type a number at the prompt, the following error message is displayed:
Cannot implicitly convert type 'int' to 'string'
The following line causes the error:
lives = Console.ReadLine();
The lives field is an integer. How can I correctly assign a user-entered value to an integer field?
Here is my complete code:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
namespace ConsoleApplication6
{
class Hangman
{
//guesses
public static int lives = 5;
//Words for the game
static string[] wordBank = { "study", "cat", "dress", "shoes", "lipstick" };
// Create new ArrayList and initialize with words from array wordBank
static ArrayList wordList = new ArrayList(wordBank);
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Title = "C# Hangman";
Console.WriteLine("Hang man!");
//Gamemenu
string response = "";
do
{
Console.Write("Enter Command (1. Add Words, 2. List Words , 3. Play , 4. Exit) Pick 1-4: ");
response = Console.ReadLine();
switch (response)
{
case "1": AddWord(); break;
case "2": ListWords(); break;
case "3": Play(); break;
case "4": break;
}
} while (response != "4");
}
//add words to list
static void AddWord()
{
Console.Write("Enter the word to add: ");
String temp = Console.ReadLine();
wordList.Add(temp);
Console.WriteLine("{0} was added to the dictionary!", temp);
}
//Display words
static void ListWords()
{
foreach (Object obj in wordList)
Console.WriteLine("{0}", obj);
Console.WriteLine();
}
//How many guesses
static void AskLives()
{
try
{
Console.WriteLine("please enter number of lives?");
//This line gives me the error
lives = Console.ReadLine();
}
catch
{
// if user does not enter a number ask it again
AskLives();
}
}
//Gameplay
static void Play()
{
Random random = new Random((int)DateTime.Now.Ticks);
string wordToGuess = wordList[random.Next(0, wordList.Count)].ToString();
string wordToGuessUppercase = wordToGuess.ToUpper();
StringBuilder displayToPlayer = new StringBuilder(wordToGuess.Length);
for (int i = 0; i < wordToGuess.Length; i++)
displayToPlayer.Append('-');
List<char> correctGuesses = new List<char>();
List<char> incorrectGuesses = new List<char>();
bool won = false;
int lettersRevealed = 0;
string input;
char guess;
AskLives();
while (!won && lives > 0)
{
Console.WriteLine("Current word: " + displayToPlayer);
Console.Write("Guess a letter: ");
input = Console.ReadLine().ToUpper();
guess = input[0];
if (correctGuesses.Contains(guess))
{
Console.WriteLine("You've already tried '{0}', and it was correct!", guess);
continue;
}
else if (incorrectGuesses.Contains(guess))
{
Console.WriteLine("You've already tried '{0}', and it was wrong!", guess);
continue;
}
if (wordToGuessUppercase.Contains(guess))
{
correctGuesses.Add(guess);
for (int i = 0; i < wordToGuess.Length; i++)
{
if (wordToGuessUppercase[i] == guess)
{
displayToPlayer[i] = wordToGuess[i];
lettersRevealed++;
}
}
if (lettersRevealed == wordToGuess.Length)
won = true;
}
else
{
incorrectGuesses.Add(guess);
Console.WriteLine("Nope, there's no '{0}' in it!", guess);
lives--;
}
Console.WriteLine(displayToPlayer.ToString());
}
if (won)
Console.WriteLine("You won!");
else
Console.WriteLine("You lost! It was '{0}'", wordToGuess);
Console.Write("Press ENTER to exit...");
Console.ReadLine();
}
}
}
Your lives field is an integer, but Console.ReadLine returns a string.
You can use Int32.Parse(Console.ReadLine()) to parse the input into an integer. Note that an exception will be thrown if the text entered by the user cannot be interpreted as an integer.
Your catch block will work here and re-prompt. It would be more appropriate to use the Int32.TryParse method:
int tmpLives;
if (Int32.TryParse(Console.ReadLine(), out tmpLives))
{
lives = tmpLives;
}
else
{
AskLives();
}
You want to do something along the lines of:
string livesString = Console.ReadLine();
lives = Convert.ToInt32(livesString);
I'm guessing Console.ReadLine() gives you a string. This will not play ball with your integer lives. You could try this:
lives = Int.Parse(Console.ReadLine())

c# iteration with no answer first 2 times. Output on third try over and over again

I wrote this as a simple dice game. It works as I want except it iterates 3 times with no answer on the first two iterations. The third time the question is asked and answered a output shows up.
No idea where in my code is the issue, I have gone over it over and over....lol any help =)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/* I am very confused but for soem reason it only returns a value every 3 tries....I dont understand
* I looked through the program and the only thing that occurs 3 times is the if else if else if statement
* but I dont see how that would do it....
*/
namespace Lab11
{
class Program
{
static void Main(string[] args)
{//declared constants
const int NUM_1 = 1;
const int NUM_6 = 6;
Console.WriteLine("\t\t\tWelcome To a Game of Dice!");
//Do while statement repeating the "roll again" question and performing the random numbers
do
{
Again();
Random ran = new Random();
//if else if else if statement doing the random numbers and telling you rolled snake or box
if (Again() == true)
{
int num1 = ran.Next(1, 7);
int num2 = ran.Next(1, 7);
//if else statement determining the output for each roll in the console.
if (num1 == NUM_6 && num2 == NUM_6)
{
Console.WriteLine("\nYou Rolled BoxCars");
}
else if (num1 == NUM_1 && num2 == NUM_1)
{
Console.WriteLine("\nYou rolled Snake-Eyes");
}
else
{
Console.WriteLine("\nYou Rolled...{0} and {1}", num1, num2);
}
}
} while (Again() == true);
//Goodbye if you press 'n'
Console.WriteLine("\n\nGoodBye");
Console.ReadLine();
}
//the yes or no method asking if you want to play again
//this is where I think the issue is but I dont see where or how....
static bool Again()
{
char response;
Console.Write("\n\nWould you like to roll the dice (y or n)? ");
response = char.Parse(Console.ReadLine());
response = char.ToLower(response);
if (response == 'y')
return true;
else
return false;
}
}
}
Again();
Random ran = new Random();
if (Again() == true)
{
// ...
Here, you are calling Again() twice, which causes it to prompt the user twice. You could change it like this:
bool rollAgain = Again();
Random ran = new Random();
if (rollAgain == true)
{
// ...
You have a similar issue here:
} while (Again() == true);
To solve everything, you could probably introduce the rollAgain variable outside the do-while statement and assign it inside.
You are calling Again way too many times. Do something like this instead:
Console.WriteLine("\t\t\tWelcome To a Game of Dice!");
while (Again()) {
Random ran = new Random();
int num1 = ran.Next(1, 7);
int num2 = ran.Next(1, 7);
if (num1 == NUM_6 && num2 == NUM_6) { ...
else .. // the rest of your checking code here
}
So now you are only calling Again once per loop. If you step through the code (including stepping into Again), you should be able to see what's happening.
You can use while loop here, and call Again one time
while (Again())
{
Random ran = new Random();
int num1 = ran.Next(1, 7);
int num2 = ran.Next(1, 7);
//if else statement determining the output for each roll in the console.
if (num1 == NUM_6 && num2 == NUM_6)
{
Console.WriteLine("\nYou Rolled BoxCars");
}
else if (num1 == NUM_1 && num2 == NUM_1)
{
Console.WriteLine("\nYou rolled Snake-Eyes");
}
else
{
Console.WriteLine("\nYou Rolled...{0} and {1}", num1, num2);
}
}

Validation of input - Numbers vs. Letters

I am creating a short C# console program that will ask 10 addition questions using random numbers from 0-10. Then it tells the user how many correct or incorrect answers they had. I am trying to find a way to validate that my user input is a number and not a letter. I am posting the code I have created so far, but could use some help.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int i = 0;
int input;
int correct = 0;
int incorrect = 0;
int questions = 10;
int[] solutions = new int[21];
int[] answers = new int[21];
int[] number1 = new int[21];
int[] number2 = new int[21];
Random number = new Random();
Console.WriteLine(" This is a test of your basic addition skills. ");
Console.WriteLine(" Please answer the random addition question below ");
Console.WriteLine(" with a number from 1 - 20 and press enter to get the");
Console.WriteLine(" next of 10 questions. At the end of the questions");
Console.WriteLine(" your results will be calculated and presented to you.");
Console.WriteLine("");
Console.WriteLine("");
while (i < questions)
{
number1[i] = number.Next(0, 10);
number2[i] = number.Next(0,10);
solutions[i] = (number1[i] + number2[i]);
//Console.WriteLine("{0} + {1} = {2}", number1[i], number2[i],solutions[i]);
Console.Write(" {0} + {1} = ", number1[i], number2[i]);
answers[i] = Convert.ToInt32(Console.ReadLine()); // original code
//input = Convert.ToInt32(Console.ReadLine());
//if (input > 0 && input <21)
//{
// Console.WriteLine("YOur answer is: {0}", input);
//}
//else
//Console.WriteLine("YOur answer is not valid");
if (solutions[i] == answers[i])
{
Console.WriteLine(" Correct");
correct++;
}
else
{
Console.WriteLine(" Your answer is incorrect, the correct answer is {0}", solutions[i]);
incorrect++;
}
//Console.WriteLine("{0}", answers[i]);
//int sum = numberone + numbertwo;
//answers[sum]++;
i++;
}
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("The number correct is: {0}, The number incorrect is: {1}", correct, incorrect);
}
}
}
Use int.TryParse() like:
bool isNumber=false;
int number;
while (!isNumber)
{
string txt = Console.ReadLine();
if (!int.TryParse(txt, out number))
{
// not a number, handle it
Console.WriteLine("This is not a number, enter a number. For real now.");
}
else
{
// use number
answers[i] = number;
isNumber = true;
}
}
Instead of:
answers[i] = Convert.ToInt32(Console.ReadLine()); // original code
Use:
int input;
bool validInput = int.TryParse(Console.ReadLine(), out input);
if (!validInput || input < 0 && input > 20)
<throw exception or display some error message here...>
EDIT: If you want to recursively ask for a correct input, this is how you can do it:
int input;
bool validInput = false;
while (!validInput)
{
validInput = int.TryParse(Console.ReadLine(), out input);
if (!validInput || input < 0 && input > 20)
{
validInput = false; // We need to set this again to false if the input is not between 0 & 20!
Console.WriteLine("Please enter a number between 0 and 20");
}
}
int iResult = int.MinValue;
bool bParsed = int.TryParse("xyz", out iResult);
TryParse will not throw an exception.
However, you can use Convert.ToInt32() as well if needed but that will throw an exception on bad data.
Something like:
if (int.TryParse(Console.ReadLine(), out answers[i]) && answers[i] > 0 && ...)
{
...
}
else
{
// invalid answer
}
This allows you to fill all positions of your array:
int result;
bool isInt = Int32.TryParse(Console.ReadLine(), out result);
if (!isInt) {
Console.WriteLine("Your input is not an integer number.");
continue;
}
answers[i] = result;

Categories

Resources