public void PlayerChooseDraw()
{
Deck deck = new Deck();
Console.WriteLine("Number of cards in the deck is: " + deck.CardCount);
Console.WriteLine("-------------");
Console.WriteLine("How many cards do you want to draw? You can draw between 1 to 26");
int playerDraw = Convert.ToInt32(Console.ReadLine());
if (playerDraw > 26) {
Console.Clear();
Console.WriteLine("ERROR: Maximum cards to draw is 26 !");
PlayerChooseDraw();
}
else if (playerDraw < 1) {
Console.Clear();
Console.WriteLine("ERROR: Minimum cards to draw is 1 !");
PlayerChooseDraw();
}
else {
Console.Clear();
DeckCreation(playerDraw);
}
}
public void DeckCreation(?)
{
Console.WriteLine(playerDraw);
}
How can I bring the integer variable playerDraw to DeckCreation method without changing it to string or something other? Thank you.
You can direcly pass the integer to be printed by the method like this:
public void PrintNumberOfCards(int count)
{
Console.WriteLine(count.ToString());
}
I renamed playerDraw to countCardsToDraw to be more clean and relevant, thus we can call the method like that:
int countCardsToDraw = Convert.ToInt32(Console.ReadLine());
...
PrintNumberOfCards(countCardsToDraw);
Also we can use int.TryParse to manage errors:
int.TryParse(Console.ReadLine(), out var countCardsToDraw);
Here the value will be 0 in case of non integer entered.
We can check the result to loop on the user input and validate the value:
bool isUserInputValid;
do
{
Console.WriteLine("How many cards do you want to draw? You can draw between 1 to 26:");
isUserInputValid = int.TryParse(Console.ReadLine(), out var countCardsToDraw)
&& countCardsToDraw >= 1
&& countCardsToDraw <= 26;
if ( !isUserInputValid )
Console.WriteLine("Wrong value, retry.");
}
while ( !isUserInputValid );
Related
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 am attempting to get some data validation done but I am really struggling with that. I have been using If statements and was hoping If (pun intended) someone could help me. I am very new to the whole thing and have a massive piece that needs to be done so far I have managed but this got me stumped. I really would like a push or something in the correct direction because it feels like I am rubbing my head against a piece of sandpaper
int iNumber1;
int iNumber2;
Console.WriteLine("Please give me 2 number between -10 and +10 and ill add them together");
Console.Write("Please enter a number: ");
iNumber1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter a number: ");
iNumber2 = Convert.ToInt32(Console.ReadLine());
int iResult;
//here i get the adding bit done
iResult = iNumber1 + iNumber2;
//bool bUserInput = false;
//while (!bUserInput)
//{
// string sInput = Console.ReadLine();
// if (iNumber1 < -10)
// {
// Console.WriteLine("Your are out of range please stay between -10 and +10");
// }
// if (iNumber1 < 10)
// {
// Console.WriteLine("Your are out of range please stay between -10 and +10 ");
// }
// if (iNumber2 < -10)
// {
// Console.WriteLine("Your are out of range please stay between -10 and +10");
// }
// if (iNumber2 < 10)
// {
// Console.WriteLine("Your are out of range please stay between -10 and +10");
// }
//}
if (iResult <= -10 || iResult >= 11)
{
Console.WriteLine("Out of range calculation is ignored");
}
else
{
Console.WriteLine("That number is vaild and its {0}", iResult);
}
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Please give me 2 number between -10 and +10 and ill add them together\n");
int iNumber1 = readNumber();
int iNumber2 = readNumber();
int iResult = iNumber1 + iNumber2;
Console.WriteLine("The sum of {0} + {1} is {2}", iNumber1, iNumber2, iResult);
}
//you should use functions to avoid code repetition.
//the function below reads the user input and tries to convert it into a number.
//the validation rule is applied inside the loop.
private static int readNumber()
{
bool bUserInput;
int number;
//below is a loop that runs at least once. the loop continues
//iterating while the condition evaluates to true, otherwise it ends
//and control goes to the statement immediately after it.
do
{
Console.WriteLine("Please enter a number: ");
//Int32.TryParse receives as arguments a string to parse and
//an integer as an output argument (you need the out keyword)
//it returns true if it the string could be successfully converted
//into an integer and false if it couldn't.
bUserInput = Int32.TryParse(Console.ReadLine(), out number);
if (!bUserInput)//this will be true if the user input could not be converted
{
Console.WriteLine("Input could not be converted into an integer number");
//the continue statement is used inside a loop to skip the rest of it
//and jump directly to the test condition
continue;
}
if (number < -10 || number > 10)//the validation
{
//the error message
Console.WriteLine("Your are out of range please stay between -10 and +10");
//make sure we set the flag to false because in this case,
//Int32.TryParse has set it to true, but input is still invalid
//by the validation rules.
bUserInput = false;
}
else//the number is in range, set the flag to true
{
Console.WriteLine("Good Job!\n");
//set the flag to true, so the loop can end.
bUserInput = true;
}
}while(!bUserInput);//while this evaluates to true, the loop continues.
return number;
}
}
So you need a way to validate that a number is between -10 and +10 (inclusive). That should be easy:
bool isValid(int i)
{
return (i >= -10) && (i <= 10);
}
now you need a function to see if two numbers are both valid:
bool areValid(int i1, int i2)
{
return isValid(i1) && isValid(i2);
}
Now just assume that input is not valid, and loop until it is:
bool isValid = false;
while(!isValid)
{
Console.WriteLine("Please give me 2 number between -10 and +10 and I'll add them together");
Console.Write("Please enter a number: ");
iNumber1 = Convert.ToInt32(Console.ReadLine());
Console.Write("Please enter a number: ");
iNumber2 = Convert.ToInt32(Console.ReadLine());
isValid = areValid(iNumber1, iNumber2);
if(!isValid)
{
Console.WriteLine("Out of range calculation is ignored");
}
}
Now you know you have two valid numbers and can continue with the rest of your program.
I am programming a game that generates a random number and then has the user try to guess the number when the user inputs a number the program will respond with either too high or too low depending on the number generated.The problem I am having is that the loop will just keep executing and the program will not take another user input if the number is incorrect.I have tried using different types of loops like a do while and for loop but keep getting the same problem I feel as though I am missing something simple or making a simple mistake thanks
string usernumber;
Random rnd = new Random();
int value = rnd.Next(1,50); //generates a random number upto 50
int guess = 0;
Console.WriteLine("please enter a number"); //asks for and takes user input
usernumber = Console.ReadLine();//stores user input
guess = Convert.ToInt32(usernumber);
while (guess != value) //this stands for not equals to
{
//guess = Convert.ToInt32(usernumber);
if (value > guess)
{
Console.WriteLine("too high");
}
else if (value < guess)
{
Console.WriteLine("too low");
}
else if (value == guess)
{
Console.WriteLine("bang on the answer was" + value);
}
else
{
Console.WriteLine("errrrrrrrrr");
}
}
Thread.Sleep(2000); //delays the program closing for a bit
You can use this corrected and refactored to have more explicit variables names.
We add 1 to 50 because the Random.Next last parameter is the upper bound excluded.
We use a do...while loop to have a concise algorithm.
We use int.TryParse to get the int from the user. This method returns false and sets the value to 0 in case of conversion error instead of an exception.
We use Console.ReadKey instead of Thread.Sleep, that is more UX friendly.
var random = new Random();
int numberTarget = random.Next(1, 50 + 1);
int numberUser;
do
{
Console.Write("Please enter a number between 1 and 50: ");
if ( int.TryParse(Console.ReadLine(), out numberUser) )
{
if ( numberUser > numberTarget )
{
Console.WriteLine("Too high, retry.");
}
else
if ( numberUser < numberTarget )
{
Console.WriteLine("Too low, retry.");
}
else
{
Console.WriteLine($"Bang on the answer was {numberTarget}.");
}
}
else
{
Console.WriteLine("You didn't enter a valid number, retry.");
}
}
while ( numberUser != numberTarget );
Console.WriteLine("Press a key to exit.");
Console.ReadKey();
In your while loop, you forgot to make another ReadLine.
while (guess != value) //this stands for not equals to
{
if (value > guess)
{
Console.WriteLine("too high");
guess = Convert.ToInt32(Console.ReadLine());
}
else if (value < guess)
{
Console.WriteLine("too low");
guess = Convert.ToInt32(Console.ReadLine());
}
else if (value == guess)
{
Console.WriteLine("bang on the answer was" + value);
}
else
{
Console.WriteLine("errrrrrrrrr");
}
}
Having problem with my work i want to write a program that does the sum and average the student grade in the average function i used a do while loop since i want anyone to enter grade until the user enter -1 the loop end.
The problem is i do not want to run the _cal = Int32.Parse(Console.ReadLine()); in the fucntion instead run it in the main by passing a value to Average() parameter then using the value in main as a console.readlIne because i will use the user input to divide by the sum in order to get average am new to programming.
public static void Main()
{
Console.WriteLine("Please Enter the scores of your student: ");
Console.WriteLine("----------------------------------------");
_studentTotalGrade = Average();
Console.WriteLine("sum " + Sum);
Console.ReadLine();
}
public static double Average()
{
double _cal,_sumTotal = 0;
int i = 0;
do
{
_cal = Int32.Parse(Console.ReadLine());
if (_cal == -1)
{
break;
}
if (_cal > 20)
{
Console.WriteLine("Adjust score\");
continue;
}
_sumTotal +=_cal;
i--;
} while (_cal > i);
return _sumTotal;
}
}
This is the code that I have made that rolls two dice until a pair appear.
My question is, is there a way for the user to enter any amount of dice he/she wants?
I don't want to create 50 int dice. If I use an array or List I would have the same problem. I'd have to assign each array section to numbergen 50 or more times. Maybe there is something I am missing?
static void Main(string[] args)
{
Random numbergen = new Random();
int dice1=0;
int dice2=1;
for (int counter = 0; counter <= 1; counter++)
{
while (dice1 != dice2)
{
dice1 = numbergen.Next(1, 7);
dice2 = numbergen.Next(1, 7);
if (dice1 == dice2)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(dice1 + "\t" + dice2);
counter++;
dice1 = 0;
dice2 = 1;
}
else if (dice1 != dice2)
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(dice1 + "\t" + dice2);
}
if (counter ==1 )
{
break;
}
}
}
Console.ReadLine();
}
Here's a version where all die must match.
using System;
namespace Dicey
{
class Program
{
static void Main(string[] args)
{
int numberOfDice;
// check for and retrieve the number of dice the user wants.
if (args.Length != 1 || !int.TryParse(args[0], out numberOfDice))
{
Console.WriteLine("Please provide the number of dice.");
return; // exit because arg not provided
}
// Must have at least one and set some arbitrary upper limit
if (numberOfDice < 1 || numberOfDice > 50)
{
Console.WriteLine("Please provide a number of dice between 1 and 50");
return; // exist because not in valid range
}
var dice = new int[numberOfDice]; // create array of die (ints)
var rand = new Random();
var match = false; // start with false (match not found yet)
while (!match) // loop until match becomes true
{
var message = string.Empty;
match = true; // assume match until something doesn't match
for (var i = 0; i < numberOfDice; i++)
{
// initialize dice at index i with the random number
dice[i] = rand.Next(1, 7);
// build the message line to write to the console
message += dice[i]; // first add the die's number
if (i < numberOfDice - 1)
message += "\t"; // if not at the end, add a tab
// check if the previous die (except for the first of course) has a different number
if (i > 0 && dice[i - 1] != dice[i])
match = false; // uh oh, not all match. we have to keep going
}
// print out the message
Console.ForegroundColor = match ? ConsoleColor.Yellow : ConsoleColor.White;
Console.WriteLine(message);
}
Console.ReadLine();
}
}
}
If you want to store a number of integers specified by the user, then the easiest way to do that would be using an array like int x[z] where z is the number specified by the user, or, even better, make a list of ints in the form List<int> where you can add ints depending on the number the user entered.
You wouldn't have the same problem as if you had many different variables when doing numbergen, because you could just have a for loop go through your list or array, giving them a value assigned by numbergen.
Try this,
Ask user to enter a number of dice store it in a variable then create an array of that size.