C# console app random number generation - c#

How can I get the random number generator method to loop and produce new random numbers? Do I need a separate class before Main that handles the random number generation? If so, how do I get the scope of those variables to Main? The console app is supposed to repeat integer math problems to practice with a loop that conditions on correct or incorrect answer. Also, what syntax am I overlooking to loop back to a new instance of randomly generated integers? TIA.
public class Multiplication
{
public static void Main(string[] args)
{
Random randomNumbers = new Random(); // random number generator
int num01 = randomNumbers.Next(1, 11);
int num02 = randomNumbers.Next(1, 11);
int value = 0;
while (true)
{
if (value != -1)
{
Console.Write("Please enter the answer to {0} x {1} = ?", num01, num02);
int product = num01 * num02;
Console.WriteLine();
int answer = Convert.ToInt32(Console.ReadLine());
while (product != answer)
{
Console.WriteLine("Incorrect, enter another guess: ");
answer = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Correct. Your answer was {0} \n {1} x {2} = {3} Very good!",
answer, num01, num02, product);
//keep console open
Console.WriteLine();
Console.WriteLine("Press - 1 to exit");
value = Convert.ToInt32(Console.ReadLine());
}
else
{
break;
}
}
}
}

Put the random number generation inside the loop, not before it.
int value = 0;
while (true)
{
if (value != -1)
{
int num01 = randomNumbers.Next(1, 11);
int num02 = randomNumbers.Next(1, 11);
...

The random number generator statement had to be in the loop. And I needed to tweak the console.writeline to include "type 1 to continue". So the final code is:
public class Multiplication
{
public static void Main(string[] args)
{
int value = 1;
while (true)
{
if (value == -1)
{
break;
}
else
{
Random randomNumbers = new Random(); // random number generator
int num01 = randomNumbers.Next(1, 11);
int num02 = randomNumbers.Next(1, 11);
Console.Write("Please enter the answer to {0} x {1} = ?", num01, num02);
int product = num01 * num02;
Console.WriteLine();
int answer = Convert.ToInt32(Console.ReadLine());
while (product != answer)
{
Console.WriteLine("Incorrect, enter another guess: ");
answer = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Correct. Your answer was {0} \n {1} x {2} = {3} Very good!",
answer, num01, num02, product);
//keep console open
Console.WriteLine();
Console.WriteLine("Press - 1 to exit or 1 to continue");
value = Convert.ToInt32(Console.ReadLine());
}
}
}
}

Related

C# Play Again Number Game

I'm trying to implement the ability for the user to input Y or N to play the game again or exit, but I'm struggling to get my head round it without a massive rewrite of the code logic... I'm just getting back into C# today and am a beginner so please go easy on me :) I've already got the userContinue string ready and just want to enter a simple way of repeating the game and adding on ways of keeping score (slowly improving the game)
using System;
namespace Guess_Number_V2
{
class Program
{
static void Main(string[] args)
{
do
{
PlayGame();
Console.WriteLine("Would you play to play again? Y or N");
} while (Console.ReadLine().ToLower() == "y");
}
public static voic PlayGame()
{
Random rand = new Random();
int randNum = rand.Next(1, 11);
int incorrectGuesses = 0;
int userScore = 10;
int userGuess;
int perGuess = 1;
string userContinue;
bool correctGuess = false;
Console.WriteLine("Enter a number between 1 and 10\nScore starts at 10, one point will be deducted with each incorrect guess.");
userGuess = int.Parse(Console.ReadLine());
while (correctGuess == false)
{
if (userGuess == randNum)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Your guess was right, the number was {0}! Total score is {1} and you had {2} incorrect guesses.", randNum, userScore, incorrectGuesses);
correctGuess = true;
}
if (userGuess > randNum)
{
userScore -= perGuess;
incorrectGuesses++;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Wrong guess again, to high!");
correctGuess = false;
}
else if (userGuess < randNum)
{
userScore -= perGuess;
incorrectGuesses++;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Wrong guess again, to low!");
correctGuess = false;
}
}
}
}
}
It would help if you put your game logic in its own method. Say PlayGame(). Then you can simply write:
static void Main(string[] args)
{
do {
PlayGame();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Would you play to play again? Y or N");
} while (Console.ReadLine().ToLower() == "y");
}
Also, you can simplify your logic if you make an "infinite" loop and break out of it with break; when the guess is correct.
You can read and parse the user input at the beginning of each loop.
Setting the user score the number of incorrect guesses and the red console color can be done only once also.
Tested and working code:
using System;
namespace Guess_Number_V2
{
class Program
{
static void Main(string[] args)
{
do {
PlayGame();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Would you play to play again? Y or N");
} while (Console.ReadLine().ToLower() == "y");
}
private static void PlayGame()
{
Random rand = new Random();
int randNum = rand.Next(1, 11);
int incorrectGuesses = 0;
int userScore = 10;
int userGuess;
int perGuess = 1;
Console.WriteLine("Enter a number between 1 and 10\nScore starts at 10, one point will be deducted with each incorrect guess.");
while (true) {
userGuess = int.Parse(Console.ReadLine());
if (userGuess == randNum) {
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Your guess was right, the number was {0}! Total score is {1} and you had {2} incorrect guesses.", randNum, userScore, incorrectGuesses);
break;
}
userScore -= perGuess;
incorrectGuesses++;
Console.ForegroundColor = ConsoleColor.Red;
if (userGuess > randNum) {
Console.WriteLine("Wrong guess again, to high!");
} else { // Must be userGuess < randNum
Console.WriteLine("Wrong guess again, to low!");
}
}
}
}
}

C# How do I error check the input ensuring only integers between 1-100 are accepted

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
}

How to display highest and lowest of an array

here i ask the user for homework scores which are then averaged after discarding the smallest and largest score. i have stored the user input in an array. in my DisplayResults method im not sure how to display the lowest and highest scores that were discarded. any help is appreciated! Here is what i have so far:
class Scores
{
static void Main(string[] args)
{
double sum = 0;
double average = 0;
int arraySize;
double[] inputValues;
arraySize = HowManyScores();
inputValues = new double[arraySize];
GetScores(inputValues);
sum = CalculateSum(inputValues);
average = CaculateAverage(sum, arraySize);
DisplayResults(inputValues, average);
Console.Read();
}
public static int HowManyScores()
{
string input;
int size;
Console.WriteLine("How many homework scores would you like to enter?");
input = Console.ReadLine();
while (int.TryParse(input, out size) == false)
{
Console.WriteLine("Invalid data. Please enter a numeric value.");
input = Console.ReadLine();
}
return size;
}
public static void GetScores(double[] inputValues)
{
double scoreInput;
Console.Clear();
for (int i = 0; i < inputValues.Length; i++)
{
scoreInput = PromptForScore(i + 1);
inputValues[i] = scoreInput;
}
}
public static double PromptForScore(int j)
{
string input;
double scoreInput;
Console.WriteLine("Enter homework score #{0}:", j);
input = Console.ReadLine();
while (double.TryParse(input, out scoreInput) == false)
{
Console.WriteLine("Invalid Data. Your homework score must be a numerical value.");
input = Console.ReadLine();
}
while (scoreInput < 0)
{
Console.WriteLine("Invalid Data. Your homework score must be between 0 and 10.");
input = Console.ReadLine();
}
while (scoreInput > 10)
{
Console.WriteLine("Invalid Data. Your homework score must be between 0 and 10.");
input = Console.ReadLine();
}
return scoreInput;
}
public static double CalculateSum(double[] inputValues)
{
double sum = 0;
for (int i = 1; i < inputValues.Length - 1; i++)
{
sum += inputValues[i];
}
return sum;
}
public static double CaculateAverage(double sum, int size)
{
double average;
average = sum / ((double)size - 2);
return average;
}
public static void DisplayResults(double[] inputValues, double average)
{
Console.Clear();
Console.WriteLine("Average homework score: {0}", average);
//Console.WriteLine("Lowest score that was discarded: {0}",
//Console.WriteLine("Highest score that was discarded: {0}",
}
}
}
You basically only have to do one thing: Sorting the array after you received your input data. Then, printing the first and last value gives you the minimal and maximal score. Use
Array.Sort(intArray);
in main after calling GetScores and
Console.WriteLine("Lowest score: {0} Highest score: {1}",
inputValues[0], inputValues[inputValues.Length - 1]);
to print the results. Cheers
EDIT: The proposal by Jens from the comments using the Min/Max is probably more what you're looking for if you're not interested in complete ordering of your values.

How to add user input together

My program has to add the previous number entered to the next one. This is what I have so far, and I got stuck. It adds up the number that I have entered, but I don't understand how I have to validate one number from previous.
static void Main(string[] args)
{
const int QUIT = -1;
string inputStr;
int inputInt = 0;
do
{
Console.Write("Type a number (type -1 to quit): ");
inputStr = Console.ReadLine();
bool inputBool = int.TryParse(inputStr, out inputInt);
if (inputBool == true)
inputInt += inputInt;
Console.WriteLine("Sum of the past three numbers is: {0}", inputInt);
} while (inputInt != QUIT);
}
Since there may be an indefinite number of entries, I don't know how to properly use an array.
If you are trying to find sum of numbers take another variable.
static void Main(string[] args)
{
const int QUIT = -1;
string inputStr;
int inputInt = 0,tempint=0;
do
{
Console.Write("Type a number (type -1 to quit): ");
inputStr = Console.ReadLine();
bool inputBool = int.TryParse(inputStr, out tempint);
if (inputBool == true)
{
inputInt += tempint;
}
Console.WriteLine("Sum of the past three numbers is: {0}", inputInt);
} while (tempint!= QUIT);
}
If you want the simplest solution, you can just keep track of the past 3 numbers and sum them up when you print
static void Main(string[] args)
{
const int QUIT = -1;
string inputStr;
int i1 = 0;
int i2 = 0;
int i3 = 0;
int inputInt = 0;
do
{
Console.Write("Type a number (type -1 to quit): ");
inputStr = Console.ReadLine();
bool inputBool = int.TryParse(inputStr, out inputInt);
if (inputBool == true)
{
i3 = i2;
i2 = i1;
i1 = inputInt;
}
Console.WriteLine("Sum of the past three numbers is: {0}", i1+i2+i3);
} while (inputInt != QUIT);
}
This answer uses LINQ and Queues to do what you want.
static void Main(string[] args)
{
const int QUIT = -1;
string inputStr;
int inputInt = 0;
Queue myQ = new Queue();
do
{
Console.Write("Type a number (type -1 to quit): ");
inputStr = Console.ReadLine();
bool inputBool = int.TryParse(inputStr, out inputInt);
if (inputBool == true)
{
if (myQ.Count() == 3)
{
myQ.Dequeue();
myQ.Enqueue(inputInt);
}
else
{
myQ.Enqueue(inputInt);
}
}
if (myQ.Count() == 3)
{
Console.WriteLine("Sum of the past three numbers is: {0}", myQ.Sum());
}
} while (inputInt != QUIT);
}
Use a list to store all of the numbers as they come in. Then at the end count how many items are in the list, and Sum() the entire list
static void Main(string[] args)
{
const int QUIT = -1;
string inputStr;
List<int> allNumbers = new List<int>();
do
{
Console.Write("Type a number (type -1 to quit): ");
inputStr = Console.ReadLine();
bool inputBool = int.TryParse(inputStr, out inputInt);
if (inputBool == true)
allNumbers.Add(inputInt); // Add a new element to the list
Console.WriteLine("Sum of the past " + allNumbers.Count + " numbers is: {0}", allNumbers.Sum());
} while (inputInt != QUIT);
}
you need to create a local variable to hold the output from int.TryParse. Also you do not need a do while loop, you can exit immediately when the input is -1. With these changes, keeping up with the last 3 numbers becomes much easier:
static void Main(string[] args)
{
const int QUIT = -1;
int[] last3 = new int[3];
// infinite loop, exit is done when input is -1
for(;;) {
Console.Write("Type a number (type -1 to quit): ");
var input = Console.ReadLine();
int tmp; // holds the int value of the input
if (int.TryParse(input, out tmp))
{
if (tmp == QUIT)
break; // input is -1
// input was an int, so lets move the last two towards
// the front of the array, last3[0] contained the oldest value
// which is gone now
last3[0] = last3[1];
last3[1] = last3[2];
// now overwrite the last item in the array with the newest value
last3[2] = tmp;
}
// add up the values, note if input was not a valid int, this will sum
// the last 3 valid values because the above if statement will only execute
// and change the values in the array if the user input was a number
var sum = last3[0] + last3[1] + last3[2];
Console.WriteLine("Sum of the past three numbers is: {0}", sum);
}
}

C# problems with a for loop

Can someone tell me why this doesnt work. When I enter the loop it prints everything instead of one line and get the users input. It prints Enter the integer the account numberEnter the integer the account balanceEnter the account holder lastname
Got it working thanks everyone, but now the searchaccounts doesnt work
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class accounts
{
private int[] accountnum = new int[5]; //private accountnum array of five integer account numbers
private int[] accountbal = new int[5];//private balance array of five balance amounts
private string[] accountname = new string[5];//private accntname array to hold five last names
public void fillAccounts()
{
int bal;
int accountnumber;
string name;
for (int x = 0; x < 5; ++x)
{
Console.Write("Enter the integer the account number");
accountnumber = Console.Read();
Console.Write("Enter the integer the account balance");
bal = Console.Read();
Console.Write("Enter the account holder lastname");
name = Console.ReadLine();
accountnum[x] = accountnumber;
accountbal[x] = bal;
accountname[x] = name;
}
}
public void searchAccounts()
{
Console.WriteLine("Enter the account number");
int acctnum = Console.Read();
for (int x = 0; x < 6; ++x)
{
if (x < 5)
{
if (accountnum[x] == acctnum)
{
Console.WriteLine("Account #{0} has a balance of {1} for customer {2}", acctnum, accountbal[x].ToString("C"), accountname[x]);
break;
}
}
else
{
Console.WriteLine("You entered invalid account number");
}
}
}
public void averageAccounts()
{
int sum = 0;
int avg;
for (int x = 0; x < 5; ++x)
{
sum = accountbal[x] + sum;
}
avg = sum / 5;
Console.WriteLine("The average dollar amount is {0}", avg.ToString("c"));
}
}
class assignment3_alt
{
static void Main(string[] args)
{
accounts myclass = new accounts();
string userin;
myclass.fillAccounts();
int i = 0;
while (i != 1)
{//use the following menu:
Console.WriteLine("*****************************************");
Console.WriteLine("enter an a or A to search account numbers");
Console.WriteLine("enter a b or B to average the accounts");
Console.WriteLine("enter an x or X to exit program");
Console.WriteLine("*****************************************");
Console.Write("Enter option-->");
userin = Console.ReadLine();
if (userin == "a" || userin == "A")
{
myclass.searchAccounts();
}
else if (userin == "b" || userin == "B")
{
myclass.averageAccounts();
}
else if (userin == "x" || userin == "X")
{
break;
}
else
{
Console.WriteLine("You entered an invalid option");
}
}
}
}
}
Console.Read only reads a single character. You need to use Console.ReadLine.
Console.Write("Enter the integer the account number");
accountnumber = int.Parse(Console.ReadLine());
Console.Write("Enter the integer the account balance");
bal = int.Parse(Console.ReadLine());
Console.Write("Enter the account holder lastname");
name = Console.ReadLine();
You might also want to consider using int.TryParse instead of int.Parse so that you can better handle invalid input.
For your new question it is the same error. Just replace:
int acctnum = Console.Read();
with
int acctnum = int.Parse(Console.ReadLine());
or (preferably)
int acctnum;
if (!int.TryParse(Console.ReadLine(), out acctnum))
{
Console.WriteLine("You need to enter a number");
return;
}
The first will fail if the user doesn't enter a valid integer the second will print out a nice error message and return to the loop.
This is not an answer, as other have already put up some good ones. These are just a few tips about your code.
Instead of looping with while (i != 1), never changing the value of i and terminating the loop with break, it would be better to use a do-while loop, like this:
do
{
// blah blah
} while(userin != "x" || userin != "X")
It is less confusing than having a variable with no use at all.

Categories