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.
Related
I am making a small lottery game. Everything works fine but I can't get the message I want to be displayed if the user doesn't guess the correct number to only appear once. I don't know how to get it to appear only once and I know why it appears multiple times.
static void Main(string[] args)
{
int[] userGuessNums = new int[10];
Console.WriteLine("Input 10 numbers between 1-50.");
for (int i = 0; i < userGuessNums.Length; i++)
{
try
{
Console.Write("Number " + (i + 1) + ": ");
string numbers = Console.ReadLine();
int userNumbers = Convert.ToInt32(numbers);
userGuessNums[i] = userNumbers;
}
catch
{
Console.WriteLine("Invalid input");
}
}
Console.Clear();
Random randomer = new Random();
int randomNumber = randomer.Next(1, 51);
Console.WriteLine("The numbers you have chosen:");
foreach (int element in userGuessNums)
{
Console.Write(element + " ");
}
Console.WriteLine();
Console.WriteLine("Press 'Enter' to see if you have won.");
Console.ReadLine();
Console.WriteLine("The winning number is: " + randomNumber);
for (int i = 0; i < userGuessNums.Length; i++)
{
if (userGuessNums[i] == randomNumber)
Console.WriteLine("Congratulations! You won!");
else if (userGuessNums[i] != randomNumber)
{
Console.WriteLine("Sorry, you lose.");
}
}
}
You can check to see if the random number is in the array input by the user.
Import Linq at the top of your code
using System.Linq;
And after Console.WriteLine("The winning number is: " + randomNumber); replace the for-loop with
if (userGuessNums.Contains(randomNumber))
{
Console.WriteLine("Congratulations! You won!");
}
else
{
Console.WriteLine("Sorry, you lose.");
}
Modify your last for loop like so. Loop through your array and find a winning number then set your win prompt outside the loop.
Why does this work? Let's break it down. Mainly I'm separating the prompt for the win from the loop; this is going to stop it from continually displaying, which is what you want. However, we still need to isolate the element within the array that is an acceptable condition. By setting our userWonNum outside of the for loop with a value of -1 (An impossible win condition), it protects from an accidental win. Then we loop through our array and find a winning number and assign it to that variable. Once the loop is completed, then it will move to the next block and check if we had one.
Exciting tip on this. If you loop through with more than one winning number, it will re-assign multiple times if you implement more than one winning number, but for now, it will work.
int userWonNumber = -1;
for (int i = 0; i < userGuessNums.Length; i++)
{
if (userGuessNums[i] == randomNumber)
{
userWonNumber = randomNumber;
}
}
if (userWonNumber == randomNumber)
{
Console.WriteLine("Congrats, you won!");
}
else
{
Console.WriteLine("Sorry you lost!");
}
I'm very sorry this is such an easy question, I'm just starting out. I've created code that allows a user to enter a number of random dice rolls, and outputs the sum of those rolls. I've now been asked to create a loop that repeats these steps, including the prompt, until the user types 'quit'. My issue is that my code converts the string to an integer, so typing anything kills the code. Any tips of how to insert the loop and break? My code is:
static void Main(string[] args)
{
Random random = new Random();
Console.WriteLine("Enter a number of dice to roll:");
string numberDiceString = Console.ReadLine();
int numberDice = Convert.ToInt32(numberDiceString);
int total = 0;
for (int index = 0; index < numberDice; index++)
{
int DieRoll = random.Next(6) + 1;
total += DieRoll;
}
Console.WriteLine(total);
Console.ReadKey();
}
I wouldn't use a "while(true)" statement. As someone pointed out in the comments i would prefer using the right condition in there.
That being said i would do it this way:
static void Main(string[] args)
{
Random random = new Random();
string numberDiceString;
int numberDice;
Console.WriteLine("Enter a number of dice to roll:");
while ((numberDiceString = Console.ReadLine()) != "quit")
{
bool parsed = int.TryParse(numberDiceString, out numberDice);
if (!parsed)
{
//Handle the error. The user input was not a number or "quit" word
break;
}
int total = 0;
for (int index = 0; index < numberDice; index++)
{
int DieRoll = random.Next(6) + 1;
total += DieRoll;
}
Console.WriteLine(total);
Console.WriteLine("Enter a number of dice to roll:");
}
}
I have to say that i prefer this way because you can easily see when the loop will stop. Also i added an error handling that you should be doing (What happen if the user enters any words that are not numbers?).
Hope this helps.
This change should be fairly simple. What you need to do is to create a while loop, and then a check before you actually parse for an int. The psuedocode for this would be something like.
while(true) {
//Ask for input
//Check if it equals "quit"
//If so -> break;
//If not convert to int
//For Loop for dice rolls
//Print Total
}
I'm sure it could be a little more elegant than this, and you would want to put some more checks to make sure that invalid input doesn't crash the program, but it should get the job done.
This is a very simple solution that shows how to parse the user input.
using System;
namespace Simpleton
{
class Program
{
static public int GetChoice()
{
int choice = 0;
while (true)
{
Console.Write("Enter number of rolls or \"quit\" to finish: ");
var answer = Console.ReadLine();
if (String.Compare(answer, "quit", true) == 0)
{
return 0; // Done
}
if (Int32.TryParse(answer, out choice))
{
return choice;
}
}
}
static void Main(string[] args)
{
var choice = 0;
while ((choice = GetChoice()) > 0)
{
Console.WriteLine($"You'll be looping {choice} times.");
for (int tries = 0; tries < choice; tries++)
{
// Looping
}
}
}
}
}
Try this code:
static void Main(string[] args)
{
Random random = new Random();
while(true)
{
String numberDiceString = "";
int numberDice = 0;
Console.WriteLine("Enter a number of dice to roll:");
numberDiceString = Console.ReadLine();
if (numberDiceString == "quit") { return; }
int total = 0;
if (Int32.TryParse(numberDiceString, out numberDice))
{
total = 0;
for (int index = 0; index < numberDice; index++)
{
int DieRoll = random.Next(6) + 1;
total += DieRoll;
}
}
Console.WriteLine(total);
}
}
I'm not a C# programmer, but you can test for "quit" explicitly and use a goto
BeginLoop:
Console.WriteLine("Enter a number of dice to roll:");
string numberDiceString = Console.ReadLine();
if (numberDiceString == "quit")
{
goto EndLoop;
}
int numberDice = Convert.ToInt32(numberDiceString);
/* Rest of code you want to do per iteration */
goto BeginLoop;
EndLoop:
I'm creating a program for a college assignment and the task is to create a program that basically creates random times table questions. I have done that, but need to error check the input to only accept integer inputs between 1-100. I can not find anything online only for like java or for text box using OOP.
Here is my code:
static void help()
{
Console.WriteLine("This program is to help children learn how to multiply");
Console.WriteLine("The program will create times table questions from 1-10");
Console.WriteLine("The user will be given 10 random questions to complete");
Console.WriteLine("The user will get a score out of 10 at the end");
Console.WriteLine("If the user gets the answer wrong, the correct answer will be displayed");
Console.WriteLine("");
Console.ReadLine();
Console.Clear();
}
static void Main(string[] args)
{
int Random1 = 0;
int Random2 = 0;
int Answer;
int Count = 0;
int Score = 0;
int input = 0;
String choice;
Console.WriteLine("To begin the Maths test please hit any key");
Console.WriteLine("If you need any help, just, type help");
choice = Console.ReadLine();
if (choice == "help")
{
help();
}
while (Count != 10)
{
Random numbers = new Random();
Random1 = numbers.Next(0, 11);
Count = Count + 1;
Random numbers2 = new Random();
Random2 = numbers.Next(0, 11);
Console.WriteLine(Random1 + "x" + Random2 + "=");
input = int.Parse(Console.ReadLine());
Answer = Random1 * Random2;
if (Answer == input)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Correct");
Score = Score + 1;
Console.ResetColor();
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Thats the wrong answer, the correct is " + Answer);
Console.ResetColor();
}
}
if (Score > 5)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Good job you got more than 5 answers correct! With a score of " + Score + " out of 10");
Console.ResetColor();
Console.ReadLine();
}
else if (Score < 5)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("");
Console.WriteLine("Try again you got less than 5 correct! With a score of " + Score + " out of 10");
Console.ResetColor();
Console.ReadLine();
}
}
}
}
Firstly, I suggest you to use TryParse instead of Parse to prevent unexpected errors because of invalid inputs. So, try something like that;
Random numbers = new Random();
Random1 = numbers.Next(0, 11);
Count = Count + 1;
Random numbers2 = new Random();
Random2 = numbers.Next(0, 11);
Console.WriteLine(Random1 + "x" + Random2 + "=");
//Modified
int input = 0;
while (true)
{
if (!int.TryParse(Console.ReadLine(), out input))
{
Console.WriteLine("Invalid Input. Please enter a valid integer.");
}
else
{
if (input >= 1 && input <= 100)
{
break;
}
Console.WriteLine("Invalid Input. Please enter a integer between 1-100.");
}
}
//Modified
I'd simply use a loop that will keep asking for input until it
matches your requirement:
int MinVal = 1; // No magic numbers! You may consider placing them in a config
int MaxVal = 100; // or as static readonly class members (a bit like "const").
int input = -1;
for(;;) // "empty" for-loop = infinite loop. No problem, we break on condition inside.
{
// attempt getting input from user
bool parseOK = int.TryParse(Console.ReadLine(), out input);
// Exit loop if input is valid.
if( parseOK && input >= MinVal && input <= MaxVal ) break;
Console.WriteLine( "Errormessage telling user what you expect" );
}
You may also consider granting only N trys to get the input right.
A few hints:
do not use "magic numbers". Define constants or put numbers into Properties/Settings. Name them self-explanatory and document why you chose the value they happen to have.
The errormessage should tell the user what an expected valid input is (as opposed to what they typed in) not just that their input was invalid.
Whats about this?
input = int.Parse(Console.ReadLine());
if(input > 1 && input < 100){
// valid
}else{
// invalid
}
i am working on a very specific problem. this program prompts the user for a number between 1-10000000 and then another number 1-10000. the first number is how many random numbers and the second is what the max those numbers can be is. im trying to print the result on user prompt and print if user wants to print results and the result are number of primes. first problem is i cannot get the program to respond to the user pushing 1 or 0 to print results. second is i cannot get the number of primes that were created to print as a resut
namespace PRIMECON
{
class PRIMECON
{
static void Main(string[] args)
{
//creates stopwatch
Stopwatch watch = new Stopwatch();
//creates randoms
Random rnd = new Random();
//starts the stopwatch
watch.Start();
//gets number from 1 to 10 million
Console.WriteLine("\nPlease enter a number between 1 and 10,000,000");
bool checkn;
int number; //input
checkn = int.TryParse(Console.ReadLine(), out number);
//gets number from 1 to 10 thousand
Console.WriteLine("\nPlease enter a number between 1 and 10,000");
bool checkr;
int range; //range of values from 0 to r
checkr = int.TryParse(Console.ReadLine(), out range);
if (checkn == true && checkr == true && number > 0 && number <= 10000000 && range > 0 && range <= 10000)
{
//array
int arraySize = 0;
//int[] array = new int[range];
for (int i = 0; i < number; i++)
{
int randomNumber = rnd.Next(1, range);
bool primeNumber = PRIMELIB.PRIMELIB.IsItPrime(randomNumber); //calls library method
if (primeNumber == true)
arraySize++; //adds to the array for each prime number
//array[i] = randomNumber;
//prints numbers
Console.WriteLine(i.ToString() + " " + randomNumber.ToString() + " " + primeNumber.ToString()); // prints index, number, true/false
}
//int[] array = new int[arraysize];
watch.Stop();
Console.WriteLine("\nElapsed Time = " + watch.Elapsed.ToString());
int exit = 1;
do
{
Console.WriteLine("would you like to print results? 0-no 1-yes");
Console.ReadLine();
int rangeHigh;
int rangeLow;
bool high = int.TryParse(Console.ReadLine(), out rangeHigh);
bool low = int.TryParse(Console.ReadLine(), out rangeLow);
if (high == true && low == true)
{
for (int i = rangeLow; i < rangeHigh; i++)
{
//Console.WriteLine( i + ". " + array[i]);
}
}
}
while (exit != 0);
}
else if (checkn == false || number > 10000000 || number < 0)
Console.WriteLine("First number was not valid");
else if (checkr == false || range > 10000000 || range < 0)
Console.WriteLine("Range was not valid");
else
Console.WriteLine("entry not valid");
Console.ReadKey();
}
}
}
At the moment I can post an answer about your "cannot get the program to respond to the user pushing 1 or 0 to print results" issue. Since your are reading the console line within the do/while loop you can use the int.Parse function then put the inner part of the while loop in an if statement so it will only execute if the user picked yes. The loop will now become this:
int exit = 1;
do
{
Console.WriteLine("would you like to print results? 0-no 1-yes");
exit = int.Parse(Console.ReadLine());
if (1 == exit)
{
int rangeHigh;
int rangeLow;
bool high = int.TryParse(Console.ReadLine(), out rangeHigh);
bool low = int.TryParse(Console.ReadLine(), out rangeLow);
if (high == true && low == true)
{
for (int i = rangeLow; i < rangeHigh; i++)
{
//Console.WriteLine( i + ". " + array[i]);
}
}
}
}
while (exit != 0);
For your library issue with not being able to get the number of primes that were created my only suggestion is to check your references to see if you include it, and if you added the using for it at the top of your code. I have not used custom libraries in c#, but searching around in google on how to use libraries in c# will be your best bet.
I am trying to make a program that calculates some specific data from numbers given by a user.
In this example, my program counts amount of numbers in range (10,103) that are divisible by 2, and amount of numbers that are in range (15,50) divisible by 3 within numbers given by user.
On this stage, my program gives the results, when 10 numbers are given (as I specified it in the loop). How can I make my program stop reading numbers and give the results when user imputs an empty line no matter if he, entered 5 or 100 numbers before?
Here is my code, as it looks for now:
using System;
namespace Program1
{
class MainClass
{
public static void Main (string[] args)
{
int input10_103_div_2 = 0;
int input15_50_div_3 = 0;
for (int i = 0; i < 10; i++)
{
string input = Console.ReadLine ();
double xinput = double.Parse (input);
if (xinput > 10 && xinput <= 103 && (xinput % 2) == 0)
{
input10_103_div_2++;
}
if (xinput > 15 && xinput < 50 && (xinput % 3) == 0)
{
input15_50_div_3++;
}
}
Console.WriteLine ("Amount of numbers in range (10,103) divisible by 2: " + input10_103_div_2);
Console.WriteLine ("Amount of numbers in range (15,50) divisible by 3: " + input15_50_div_3);
}
}
}
instead of for, do:
string input = Console.ReadLine();
while(input != String.Empty)
{
//do things
input = Console.ReadLine();
}
if you're trying to allow any number of inputs. Or
if(input == "")
break;
if you want the for loop
Change your loop to go forever and break out of the loop when the string is empty:
for (;;)
{
string input = Console.ReadLine ();
if (String.IsNullOrEmpty(input))
{
break;
}
// rest of code inside loop goes here
}
If you want to restructure the loop, you can use a do while loop:
string input;
do{
input = Console.ReadLine();
//stuff
} while(!string.IsNullOrEmpty(input));
If you just want to be able to break early:
string input = Console.ReadLine ();
if(string.IsNullOrEmpty(str))
break;
double xinput = double.Parse (input);