I am creating a simple C# console application game that creates a random number, then displays either "too high", "too low" or "correct", it is then supposed to ask the user to input another number & then tell them whether that number is "too high", "too low" or "correct", once the right number is guessed, it should say "correct" and then display the number of guesses it took to get the correct number (this part I'm not sure how to do). Besides that I've created the code & it will tell you whether your guess is too high or too low, and once you try to enter a second guess it automatically says it's correct. How can I get the program to read more guesses, and how do I display the number of guesses?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _5.Number_Game
{
class Program
{
static void Main(string[] args)
{
double response, guess;
Random random = new Random();
int randomNumber = random.Next(1, 101);
do
{
Console.WriteLine("Enter your guess for a random number between 1 & 100");
guess = double.Parse(Console.ReadLine());
if (guess > randomNumber)
Console.WriteLine("Too high");
if (guess < randomNumber)
Console.WriteLine("Too low");
if (guess == randomNumber)
Console.WriteLine("Correct!");
Console.WriteLine("Enter another number");
response = double.Parse(Console.ReadLine());
}
while (response <= 1 && response >=100);
Console.WriteLine("Correct, Goodbye!");
Console.ReadLine();
}
}
}
Your "while" condition isn't right, it currently checks if the number is within the 1-100 range while it should check if it was the right number.
I would change it to:
while(guess != randomNumber);
or break when it is on the correct value:
if (guess == randomNumber)
{
Console.WriteLine("Correct!");
break;
}
I would also note that your "response" value is currently useless once you fix your algorithm.
You didn't need your guess as a double as the random number will only generate an integer. Also the responce variable is also not needed, as the loop can just be looped until:
while(guess != randomNumber);
Like the above answer said. If you would like to add a count of how many guesses the user takes to guess the number, add a count variable before the the opening 'do' loop.
int count = 0;
do
{
And in each guess where the user doesn't guess it correctly increment the count by one, just like this:
if (guess > randomNumber)
{
Console.WriteLine("Too high");
count += 1;
}
if (guess < randomNumber)
{
Console.WriteLine("Too low");
count += 1;
}
Then at the end when user guesses correctly
if (guess == randomNumber)
{
Console.WriteLine("Correct!");
Console.WriteLine("You took " + count + "guesses, to guess that number.");
}
Related
Hello I am trying to figure out why my program is not working, it's supposed to output a program in which department codes would be entered and followed by a prompt to enter a mark and so on until Q is entered. I can't seem to get that part working at all. If anyone could help please I will appreciate it.
// declare variables
char deptCode = ' ';
int count = 0;
double markVal, sum = 0, average = 0.0;
{
Console.WriteLine("Enter a department code: ‘C’ or ‘c’ for Computer Science,‘B’ or ‘b’ for History, ‘P’ or ‘p’ for Physics, or enter ‘Q’ or ‘q’ to quit:");
deptCode = Convert.ToChar(Console.ReadLine());
while (char.ToUpper(deptCode) != 'Q')
do
{
Console.Write("Enter a mark between 0 and 100 => ");
markVal = Convert.ToDouble(Console.ReadLine());
{
Console.WriteLine("Enter a department code: ‘C’ or ‘c’ for Computer Science,‘B’ or ‘b’ for History, ‘P’ or ‘p’ for Physics, or enter ‘Q’ or ‘q’ to quit:");
deptCode = Convert.ToChar(Console.ReadLine());
} while (markVal >= 0 && markVal <= 100);
count++;
average = (double)sum / count;
Console.WriteLine("***Error, Please Enter Valid Mark");
Console.WriteLine("The Average mark for Computer Science Students is {0}", average);
Console.WriteLine("The Average mark for Biology Students is {0}", average);
Console.WriteLine("The Average mark for Physics Students is {0}", average);
Console.ReadLine();
{
I am sympathetic to your dilemma and know it can be challenging to learn coding when you are not familiar with it. So hopefully the suggestions below may help to get you started at least down the right path. At the bottom of this is a basic “shell” but parts are missing and hopefully you will be able to fill in the missing parts.
One idea that you will find very helpful is if you break things down into pieces (methods) that will make things easier to follow and manage. In this particular case, you need to get a handle on the endless loops that you will be creating. From what I can see there would be three (3) possible endless loops that you will need to manage.
An endless loop that lets the user enter any number of discipline marks.
An endless loop when we ask the user which discipline to use
And an endless loop when we ask the user for a Mark between 0 and 100
When I say endless loop I mean that when we ask the user for a Discipline or a Mark… then, the user MUST press the “c”, “b” “p” or “q” character to exit the discipline loop. In addition the user MUST enter a valid double value between 0 and 100 to exit the Mark loop. The first endless loop will run allowing the user to enter multiple disciplines and marks and will not exit until the user presses the q character when selecting a discipline.
And finally when the user presses the ‘q’ character, then we can output the averages.
So to help… I will create two methods for you. One that will represent the endless loop for getting the Mark from the user… i.e.…. a number between 0 and 100. Then a second endless loop method that will get the Discipline from the user… i.e. … ‘c’, ‘b’, ‘p’ or ‘q’… and it may look something like…
private static char GetDisciplineFromUser() {
string userInput;
while (true) {
Console.WriteLine("Enter a department code: ‘C’ for Computer Science,‘B’ for Biology, ‘P’ for Physics, or enter ‘Q’ to quit:");
userInput = Console.ReadLine().ToLower();
if (userInput.Length > 0) {
if (userInput[0] == 'c' || userInput[0] == 'b' ||
userInput[0] == 'p' || userInput[0] == 'q') {
return userInput[0];
}
}
Console.WriteLine("Invalid discipline => " + userInput + " try again.");
}
}
Note… the loop will never end until the user selects the characters ‘c’, ‘b’, ‘p’ or ‘q’. We can guarantee that when we call the method above, ONLY those characters are returned.
Next is the endless loop to get the Mark from the user and may look something like…
private static double GetMarkFromUser() {
string userInput;
while (true) {
Console.WriteLine("Enter a mark between 0 and 100 => ");
userInput = Console.ReadLine().Trim();
if (double.TryParse(userInput, out double mark)) {
if (mark >= 0 && mark <= 100) {
return mark;
}
}
Console.WriteLine("Invalid Mark => " + userInput + " try again.");
}
}
Similar to the previous method, and one difference is we want to make sure that the user enters a valid number between 0 and 100. This is done using a TryParse method and most numeric types have a TryParse method and I highly recommend you get familiar with it when checking for valid numeric input.
These two methods should come in handy and simplify the main code. So your next issue which I will leave to you, is how are you going to store these values? When the user enters a CS 89 mark… how are you going to store this info? In this simple case… six variables may work like…
int totalsCSMarks = 0;
int totalsBiologyMarks = 0;
int totalsPhysicsMarks = 0;
double totalOfAllCSMarks = 0;
double totalOfAllBiologyMarks = 0;
double totalOfAllPhysicsMarks = 0;
Now you have something to store the users input in.
And finally the shell that would work using the methods above and you should see this uncomplicates things a bit in comparison to your current code. Hopefully you should be able to fill in the missing parts. Good Luck.
static void Main(string[] args) {
// you will need some kind of storage for each discipline.. see above...
char currentDiscipline = 'x';
double currentMark;
while (currentDiscipline != 'q') {
currentDiscipline = GetDisciplineFromUser();
if (currentDiscipline != 'q') {
currentMark = GetMarkFromUser();
switch (currentDiscipline) {
case 'c':
// add 1 to total number of CS marks
// add currentMarkValue to the total of CS marks
break;
case 'b':
// add 1 to total number of Biology marks
// add currentMarkValue to the total of Biology marks
break;
default: // <- we know for sure that only p could be left
// add 1 to total number of Physics marks
// add currentMarkValue to the total of Physics marks
break;
}
}
}
Console.WriteLine("Averages ------");
//Console.WriteLine("The Average mark for Computer Science Students is {0}", totalOfAllCSMarks / totalCSMarks);
//Console.WriteLine("The Average mark for Biology Students is {0}", ...);
//Console.WriteLine("The Average mark for Physics Students is {0}", ...);
Console.ReadLine();
}
There was a test in school where we had to write a C# console program that reads positive integers below 100 from user input and then writes out some details like the biggest number. I used a list to store the numbers. I tested it with some random numbers I typed in but the program only adds the numbers to list starting with the second smallest one.
int count = 0;
List<int> bekertek = new List<int>();
int bekert = Convert.ToInt32(Console.ReadLine());
double atlag;
while (bekert > 0 && bekert < 100)
{
bekert = Convert.ToInt32(Console.ReadLine());
count++;
bekertek.Add(bekert);
}
/* This section is only for checking the list's elements
foreach (var i in bekertek)
{
Console.Write(i + " ");
}*/
Console.WriteLine("A bevitt adatok száma: {0}", count);
bekertek.Sort();
bekertek.Remove(bekertek.Last());
atlag = bekertek.Average();
Console.WriteLine("A legnagyobb érték: {0}", bekertek.Last());
Console.WriteLine("A legkisebb érték: {0}", bekertek.First());
Console.WriteLine("Az adatok átlaga: {0}", atlag);
What did I do wrong?
For input in console, I think the do...while loop is the ideal construct. Menus or requesting a number - it covers all of those.
As for what went wrong: Actually it adds all numbers to the collection (that debug code should confirm it). You just remove the smalest number from the collection between Sorting and Display:
bekertek.Sort();
bekertek.Remove(bekertek.Last()); //Should not have done this.
atlag = bekertek.Average();
There is a saying: "The 2 most common issues in Progamming is naming variables, chache invalidation and off-by-one errors." But this specific to make is somewhat unique :)
Edit: As Biesi Grr pointed out, you also ignore the first input:
int bekert = Convert.ToInt32(Console.ReadLine()); //this is never processed
double atlag;
while (bekert > 0 && bekert < 100)
{
bekert = Convert.ToInt32(Console.ReadLine());
count++;
bekertek.Add(bekert);
}
Maybe you wanted to use a ReadKey() here? There is also no need for a counter - that is actually the job of List.Lenght. In any case, a do..while would make that line unessesary any way.
let us make a fixed, do...while version
bool repeat= true;
do{
int bekert = Convert.ToInt32(Console.ReadLine());
if(bekert > 0 && bekert < 100)
bekertek.Add(bekert);
else
repeat = false;
}while(repeat )
While loops runs through the if statement once and stops.
I am new to c#, so excuse me if I am overlooking something seemingly obvious. I am currently writing a program that visualizes the Collatz conjecture through console entries. The program begins by prompting the user to enter a natural number. The program is supposed to run that number through the formulae of the conjecture until it eventually reaches a value of 1. However, when I type in the number in console, the program runs it through one formula and crashes. It seems that is has a problem with the Double.Parse line. I already tried using the convert method and tried defining "num" as a decimal instead of a double.
{
Console.WriteLine("Enter a natural number:");
Double num = Convert.ToDouble(Console.ReadLine());
while (num != 1)
{
{
if (num % 2 == 0)
{
Console.WriteLine(num / 2);
num = Double.Parse(Console.ReadLine());
}
else
{
Console.WriteLine(num * 3 + 1);
num = Double.Parse(Console.ReadLine());
}
}
Console.ReadLine();
}
}
}
}
To be honest, I'm not positive what you're trying to achieve from the description (i.e., I have not idea what a Collatz conjecture visualization formula is), but I think I figured out what your issue is.
I think you're a little confused about Console.ReadLine(). This method pauses and waits for user input. As a result, during your first loop through the while statement, your program will pause and wait for user input. I think what you're trying to do is take the result of the formula in either the "if" or "else" section and capture that as the new value of "num."
Here is my best guess at what you're trying to achieve:
static void Main(string[] args)
{
Console.WriteLine("Enter a natural number:");
Double num = Convert.ToDouble(Console.ReadLine());
while (num != 1)
{
if (num % 2 == 0)
{
num /= 2;
Console.WriteLine(num);
}
else
{
num = num * 3 + 1;
Console.WriteLine(num);
}
}
Console.WriteLine(num);
Console.ReadLine();
}
Also, it looks like you might have an extra set of brackets within your while statement. It doesn't seem like that would compile as-is, so perhaps it is just the way in which you copied it into your question.
I have just started to learn C# this week and am trying to run a simple code that prompts the user to enter a number if they enter text, or prompts them to enter a positive number if they enter a negative one (so a boolean operation for the text, and an if statement for the negative). If they enter a valid (positive) number the program continues on with the rest of the steps.
However with this code, if the user inputs a negative, then a text, then another negative number and so forth it seems to break the loop and continue on with the next operations.
The code is part of a bigger program so I have scaled it down and pulled out only the most critical parts for it to run. Is anyone able to spot what I have missed here?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IncomeTaxCalculator
{
class IncomeTax
{
public static void Main()
{
double income;
income = income_input();
show_output(income);
}
public static double income_input()
{
double income; string income_string; bool bad_value = true;
do
{
Console.Write("What is your total income: ");
income_string = Console.ReadLine();
if (double.TryParse(income_string, out income))
{
bad_value = false;
}
else
{
Console.WriteLine("Enter your income as a whole-dollar numeric figure.");
}
if (income < 0)
{
Console.WriteLine("Your income cannot be a negative");
}
} while (bad_value || income < 0);
return income;
}
public static void show_output(double income)
{
Console.WriteLine("Your income is " + income);
Console.WriteLine("\n\n Hit Enter to exit.");
Console.ReadLine();
}
}
}
Here's what's happening. When you enter a negative number bad_value will be set to false. Then when you enter a non-numeric value income will be set to 0 by the TryParse. Now your condition of bad_value || income < 0 is false. To fix it you just need to reset bad_value to true at the beginning of each loop.
Alternatively you could as René Vogt suggests set bad_value to true in the else and additionally in the if that checks if it is negative and then you can just do while(bad_value).
do
{
Console.Write("What is your total income: ");
income_string = Console.ReadLine();
if (double.TryParse(income_string, out income))
{
bad_value = false;
}
else
{
Console.WriteLine("Enter your income as a whole-dollar numeric figure.");
bad_value = true;
}
if (income < 0)
{
Console.WriteLine("Your income cannot be a negative");
bad_value = true;
}
} while (bad_value);
I realize this has already been accepted but this can be done in a much simpiler loop. Why not just create an infinite loop and break/return when the values are satisfied. Instead of checking for invalid input search for valid input.
I wont go into detail as to why this is a more acceptable solution, consider the instructions given, if you exepect an invalid input then your instructions are wrong. Instead check for positive results. Read This!!
static double income_input()
{
double income = double.NaN;
while (true)
{
Console.WriteLine("What is your income?:");
if (double.TryParse(Console.ReadLine(), out income) && income > 0)
return income;
Console.WriteLine("Invalid input. Please enter a valid number greater than zero.");
}
}
Really all we have done here is created an infinite-loop with the while(true). So now the loop can never end unless we explicitly tell it to.
Next you can simply parse the result and assure the conditions that double.TryParse succeeds and income > 0. Note the return simply exits the loop.
Now this compiles (note there is no return at the end) as the compiler understands that the only exit point is through the return statement. Example Post
If you wanted to go for the shortest code possible could use some C# 7 syntax for inline variables.
static double income_input()
{
while (true)
{
Console.WriteLine("What is your income?:");
if (double.TryParse(Console.ReadLine(), out double income) && income > 0)
return income;
Console.WriteLine("Invalid input. Please enter a valid number greater than zero.");
}
}
Happy Coding!.
Change your code to be something like this:
double income;
string income_string;
do
{
Console.Write("What is your total income: ");
income_string = Console.ReadLine();
} while (!double.TryParse(income_string, out income) || income < 0);
//rest of your code here, in another method that takes the valid income
You should split the method that procures income from the one that has (business ) logic in it.
I am trying to create a mastermind game without using arrays that generates 5 random numbers 1-9, and you have 15 tries to guess them.*=Correct -=WRONG +=incorrect positionbut the number is right.
I created the first part of it, and it works for trying to guess the first random digit of 1-9. I am unsure of how to goto the second number for the player to guess the second 1-9 digit, and how to make the code keep using the same int's/keep adding onto the guesses that I set up already. I tried everyway I knew how and I can't figure it out. If I could get some assistance of where I am going wrong, and how to set it up correctly it would be very much appreciated. Cheers
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Decisions
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Guess the 5 Digit code, Under 15 tries!");
Random myRandom = new Random();
Int32 one = myRandom.Next(1, 10);
Int32 two = myRandom.Next(1, 10);
Int32 three = myRandom.Next(1, 10);
Int32 four = myRandom.Next(1, 10);
Int32 five = myRandom.Next(1, 10);
int guesses = 0;
bool incorrect = true;
do
{
if (guesses < 15)
Console.WriteLine("Guess a number between 1 and 9");
string result = Console.ReadLine();
guesses++;
if (guesses > 15)
Console.WriteLine("You went over 15 tries! Better luck next time");
if (result == one.ToString())
incorrect = false;
else if (result == two.ToString())
Console.WriteLine("+");
else if (result == three.ToString())
Console.WriteLine("+");
else if (result == four.ToString())
Console.WriteLine("+");
else if (result == five.ToString())
Console.WriteLine("+");
else
Console.WriteLine("-");
} while (incorrect);
if (guesses < 15)
Console.WriteLine("*Correct! It took {0} guesses.", guesses);
if (guesses > 15)
Console.WriteLine("You took to many tries! Better luck next time! Total Guesses: {0}", guesses);
Console.ReadLine();
}
}
}
I think what you're looking to use is a list. But first -
Keep in mind you want to be careful about how you order things in your program, especially when it comes to user experience. For instance:
if (guesses < 15)
Console.WriteLine("Guess a number between 1 and 9");
string result = Console.ReadLine();
guesses++;
if (guesses > 15)
Console.WriteLine("You went over 15 tries! Better luck next time");
So, when guesses is 14, it will show the text, have the user guess and increment "guesses" - however, when it iterates back to the beginning, your program will skip over the prompt: "Guess a number between 1 and 9" - but it will still wait for the users input. After they put in their input it will prompt that they went over the amount of tries, but it will still check if that number matched! How you order your program can be very important to a users experience.
Your program can look something like this:
const int iMaxGuesses = 15;
const int iListSize = 5;
static void Main(string[] args)
{
Random myRandom = new Random();
// Hold a list of integers
List<int> numbers = new List<int>();
int guesses = 0;
// Value where we will rebuild the code
string result = string.Empty;
// Placeholder for user's guess
string strGuess;
// Converted guess
int guess;
// Generate random list of numbers
for (int i = 0; i < iListSize; i++)
numbers.Add(myRandom.Next(1, 10));
// Prompt user
Console.WriteLine("Guess the {0} Digit code, Under {1} tries!", iListSize, iMaxGuesses);
// Open the game loop
do
{
// Check if we have exceeded the max amount of times we get to guess
if (guesses > iMaxGuesses)
Console.WriteLine("You went over 15 tries! Better luck next time");
else
{
// Prompt user
Console.WriteLine("Guess a number between 1 and 9");
// Get input
strGuess = Console.ReadLine();
// Check if input is in fact an integer, if so - put the value in our variable 'guess'
if (int.TryParse(strGuess, out guess))
{
// We have a proper guess, increment
guesses++;
// Checks if the number is the next in our list
if (numbers[0] == guess)
{
Console.WriteLine("Congratulations, {0} was a match!", guess);
// Remove that from the List
numbers.Remove(numbers[0]);
// Add it to our sequence (result)
result += guess;
}
else if(numbers.Contains(guess))
Console.WriteLine("Right number, wrong spot!");
else
Console.WriteLine("Incorrect, please try again!");
}
else // Inform user we will only accept numbered input
Console.WriteLine("That was not a number. Please try again!");
}
} while (guesses <= iMaxGuesses && numbers.Count > 0);
if (guesses < iMaxGuesses)
Console.WriteLine("Correct! It took {0} guesses to come up with the pattern {1}", guesses, result);
else
Console.WriteLine("You took to many tries! Better luck next time! Total Guesses: {0}", guesses);
Console.ReadLine();
}
Couple things to note: We have class-level constants for the List Size (we'll get to that) and how many guesses, in case these need to be changed on the fly. You can ignore this.
The first thing you may notice is a List of integers List<int> numbers = new List<int>() Here is some Reading (what is difference between string array and list of string in c#) about the differences between Arrays and Lists (collections).
We initialize the list of Random numbers by creating a loop the max size of our list, and ADDING a random integer to that list.
On the Do/While loop, we are checking that we are still less than iMaxGuesses and we have objects left in our list. So we take the users input. First we use int.TryParseto determine if we do actually have a number. If we do have a number, we will check that against the first number that appears in the list, numbers[0], and if it does, we remove it from the list: numbers.Remove(numbers[0]); The cool part about lists, is that when you REMOVE an item, it resizes the list, unlike an array that has a fixed size. So if your list is 12345, and you remove the 1, the next time you check the value of numbers[0], it will be 2!
I'm pretty sure the rest should be self explanatory. Let me know if anything was missed or you need help understanding anything.