am trying to make a mastermind game using an array of ints where I having the user guess a number sequence between 4-10 instead of colours. My GetAValidNumber is suppose to displays a prompt to the user and
get a number from the user in the minimum/maximum range as specified in
the parameters. If the number entered is outside the minimum/maximum
range, then an error message is suppose to be displayed and
the user is re-prompted for the number but for some reason it isn't validating properly.
Any Guidance would be appreciated
public static int GetAValidNumber(string inputMessage)
{
// declare variables
int validInteger;
bool inputIsValid = false;
int lowValue = 1;
int highValue = 10;
while (!int.TryParse(Console.ReadLine(), out validInteger))
{
Console.WriteLine("Invalid entery - try again.");
Console.Write(inputMessage, lowValue, highValue);
do
{
while (!int.TryParse(Console.ReadLine(), out validInteger))
{
Console.WriteLine("Invalid entery - try again.");
Console.Write(inputMessage);
}
if (validInteger < lowValue || validInteger > highValue)
{
Console.WriteLine("Your number is out of Range: ");
}
else
{
inputIsValid = true;
}
} while (validInteger < lowValue || validInteger > highValue);
}
return validInteger;
}
// This method directs the play of the game
public static void PlayGame()
{
int userNumbers;
int userGuess;
int difficulty;
int randomNumbers;
Console.WriteLine("How Many Numbers Would You Like To Use When Playing(4-10): ");
userNumbers = GetAValidNumber(Console.ReadLine());
Console.WriteLine("Choose a difficulty level (1 -3");
difficulty = GetAValidNumber(Console.ReadLine());
Console.WriteLine("A 5-digit number has been chosen. Each possible digit may be the number 1, 2, 3, or 4");
Console.ReadLine();
Console.WriteLine("Enter Your Guess {0} guesses remaning", GetGameDifficulty(difficulty, randomNumbers = GetRandomNumberCount(difficulty)));
userGuess = GetAValidNumber(Console.ReadLine());
Console.WriteLine("Your Guess was {0}, Your Results are {1}", userGuess, CountHits(userGuess, randomNumbers));
Console.ReadLine();
}
Here's a simplified version of your code:
public static int GetAValidNumber(string inputMessage)
{
int validInteger = 0;
//Range between 4 to 10
int lowValue = 4;
int highValue = 10;
int.TryParse(inputMessage, out validInteger);
while (validInteger < lowValue || validInteger > highValue)
{
Console.WriteLine("Invalid entery - try again.");
inputMessage = Console.ReadLine();
int.TryParse(inputMessage, out validInteger);
}
return validInteger;
}
The issue here is you are having multiple while loops that is not validating your inputs correctly.
Take note that on your other validating number inputs you need different ranges so I would suggest setting the lowValue and highValue as extra parameters on your function:
public static int GetAValidNumber(string inputMessage, int lowValue, int highValue)
Related
I'm trying to work through a problem presented in one of my classes. The prompt is telling us to get the user to enter any numbers (can be positive, negative, or 0), while ignoring non-numeric inputs. Then we need to compute and display the average of all the numbers entered by the user. If the user doesn't give any numbers, I need to output "you didn't enter any numbers".
My main issue is that I'm not able to store and add the numbers given by the user properly. I'm fairly certain that everything before and after the while statement is sound. So, I know the issue must lie within while (enter!="Yes"||enter!="yes"||enter!="Y"||enter!="y"), but I'm not exactly sure what the issue is. Since I have variables for my average, the sum of the user given numbers, and a counter to keep track of loop iterations, I'm pretty sure my troubles are coming from my code not being in the correct order.
Console.WriteLine("Please enter any numbers, then type Yes to continue.");
string enter = Console.ReadLine();
string msg = "";
decimal average;
int counter = 0;
decimal sum = 0;
bool res = decimal.TryParse(enter, out average);
while (enter!="Yes"||enter!="yes"||enter!="Y"||enter!="y")
{
sum = decimal.Parse(enter);
Console.WriteLine("Please enter any numbers, then type Yes to continue");
enter = Console.ReadLine();
sum += counter;
counter++;
}
average = sum / counter;
msg = (res) ? $"The sum of your numbers is {average}" : "You didn't enter any numbers";
Console.WriteLine(msg);
try this one
static void Main()
{
int counter = 0;
decimal sum = 0;
bool exit=false;
do
{
Console.WriteLine("Please enter any number or type \"done\" to exit");
var enter = Console.ReadLine();
if (enter.Trim().ToLower() != "done")
{
var ok = decimal.TryParse(enter, out var num);
if(!ok) continue;
sum += num;
counter++;
} else exit=true;
} while (!exit);
var average = counter > 0 ? sum / counter:0;
var msg = average>0? $"The average of your numbers is {average}" : "You didn't enter any numbers";
Console.WriteLine(msg);
}
Here's an alternative for you to play with. Just to give you some more ideas.
string enter = "";
string[] stop = new [] { "yes", "y" };
List<int> numbers = new List<int>();
while (!stop.Contains(enter.ToLowerInvariant()))
{
Console.WriteLine("Please enter any numbers, then type Yes to continue.");
enter = Console.ReadLine();
if (int.TryParse(enter, out int number))
{
numbers.Add(number);
}
}
if (numbers.Any())
{
Console.WriteLine($"The average of your numbers is {numbers.Average()}");
}
else
{
Console.WriteLine("You didn't enter any numbers");
}
Try this......
string enter = "";
string msg = "";
decimal average;
int counter = 0;
decimal sum = 0;
decimal input;
while (enter!="Yes"&&enter!="yes"&&enter!="Y"&&enter!="y")
{
Console.WriteLine("Please enter any numbers, then type Yes to continue");
enter = Console.ReadLine();
bool res = decimal.TryParse(enter, out input);
if (res) {
sum += input;
counter++;
}
}
if (counter != 0)
{
average = sum / counter;
msg = $"The average of your numbers is {average}";
}
else {
msg = "You didn't enter any numbers";
}
Console.WriteLine(msg);
System.Threading.Thread.Sleep(5000);
I am trying to create 7 BOOM game. if you don't know the rules, everyone takes turns and says the next number but if the number can be divided by seven or contain seven you should say BOOM instead. so in my version, you insert a number and the program should show you all the numbers to that point.
So here is my problem, I succeeded in implementing the first part but I am having a problem with the second one. This is what I have until now:
class Program
{
static void Main(string[] args)
{
int num1 = int.Parse(Console.ReadLine());
int num2 = 0;
bool boolean;
while (num1>num2)
{
num2++;
if (num2%7 == 0)
{
Console.Write("BOOM, ");
}
else
{
Console.Write(num2 + ", ");
}
}
}
}
Just change your validation to:
if (num2%7 == 0 || num2.ToString().IndexOf('7') != -1)
{
// (..)
}
The IndexOf function looks for and returns the position of a substring in a string. If it is not found, it returns -1.
As pointed by #Dimitry, another option is
if (num2%7 == 0 || num2.ToString().Contains('7'))
{
// (..)
}
This uses the extension method Contains that returns true or false if the substring exists on the string.
public static void Main()
{
Console.Write("Please enter a number: ");
int number = int.Parse(Console.ReadLine());
// validate number here....
for (int i = 1; i <= number; i++)
{
string value = IsMultipleOrContains7(i) ? "BOOM" : i.ToString();
Console.WriteLine(value);
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
public static bool IsMultipleOrContains7(int number)
{
if (number % 7 == 0)
{
return true;
}
return number.ToString().Contains("7");
}
I have trouble with the logic in the GetMinimumNumber(). I know I have to assign a number to minimum to get everything started but somehow I always end up with zero when I do.
namespace Num16
{
class Program
{
static void Main(string[] args)
{
int minimum = 0, userInput;
//call GetUserInput and pass a string prompt to it
userInput = GetUserInput("Enter the first number or -1 to quit.");
//determine if the program should procede.
while (userInput >= 0)
{
minimum = GetMinimumNumber(userInput,minimum);
userInput = GetUserInput("Enter the next number or -1 to quit.");
}
Console.WriteLine("The minimum is: {0}",minimum);
}//end main()
public static int GetMinimumNumber(int userInput, int minimum)
{
int a, b;
if (userInput < minimum )
{
minimum = userInput;
return minimum;
}
else
{
return userInput;
}
}//end GetMinimumNumber()
public static int GetUserInput(string prompt)
{
Console.WriteLine(prompt);
return int.Parse (Console.ReadLine());
}//end GetUserInput()
}
}
Why does it always return 0?
You initialize minimum to 0, and you only compare it to numbers that are positive. So there is never a number that is less than minimum, and minimum remains 0.
You should initialize minimum to int.MaxValue instead.
You can use LINQ:
int[] numbers = new int[] {1, 7, -2, 3};
int min = numbers.Min();
Console.WriteLine(min);
I'm working on an application that has the user choose how many integers to enter into an array, and then has them input the numbers to be added to the array. After each number is inputted, it shows all non-duplicate integers entered by the user up to that point in a vertical list. If it isn't unique, it informs the user that it has already been inputted.
I'm not sure how to make the application list every integer entered, rather than just the most recent one.
Here's my code:
static void Main(string[] args)
{
//checks how many numbers will be entered
int manyNumbers;
Console.WriteLine("How many numbers will you enter?");
manyNumbers = Convert.ToInt32(Console.ReadLine());
int[] array = new int[manyNumbers];
//starts asking for numbers
for (int i = 0; i < manyNumbers;)
{
Console.Write("\nEnter number: ");
string entered = Console.ReadLine();
int val;
//checks to see if valid number
if (!Int32.TryParse(entered, out val))
{
Console.Write("Invalid number '{0}'", entered);
array[i++] = val;
}
//checks to see if already entered
else if (i > 0 && array.Take(i).Contains(val))
{
Console.Write("{0} has already been entered", val);
array[i++] = val;
}
//prints inputted integer
else {
array[i++] = val;
Console.WriteLine("{0}", val);
}
}
}
Just loop over the array so far printing each.
Forgive my mobile crafted code, but more or less this:
//prints inputted integer
else {
array[i++] = val;
for(int j=0 ; j<i;j++) {
Console.WriteLine("{0}", array[j]);
}
}
You may use foreach loop
foreach(int num in array)
{
Console.WriteLine("{0}", num);
}
Very Basic approach, try one of the following:
for(var x=0;x<array.length;x++)
or
foreach(var i in array)
But your use case, use HashSet data structure
Mathematically, Set is unique list of things.
try this code, it uses a Dictionary to keep the list in memory and to search to see if the an integer has been added,
using System.Collections.Generic;
static void Main(string[] args)
{
//checks how many numbers will be entered
int manyNumbers;
Console.WriteLine("How many numbers will you enter?");
manyNumbers = Convert.ToInt32(Console.ReadLine());
Dictionary<int, int> array = new Dictionary<int, int>();
//starts asking for numbers
for (int i = 0; i < manyNumbers; )
{
Console.Write("\nEnter number: ");
string entered = Console.ReadLine();
int val;
//checks to see if valid number
if (!Int32.TryParse(entered, out val))
{
Console.Write("Invalid number '{0}'", entered);
}
//checks to see if already entered
else
if (i > 0 && array.ContainsKey(val))
{
Console.Write("{0} has already been entered", val);
//array[i++] = val;
}
else
{
//* add the new integer to list
array.Add(val, 0);
//prints the complete list
List<int> keys = new List<int>(array.Keys);
Console.WriteLine();
for(int j=0; j<keys.Count; j++) Console.WriteLine(keys[j]);
}
}
}
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;