I created a program in C# (Console Application), which prompts the user to enter the answer to "2+2=?", if its right a message pops up "Well done", if not then "Please try again". What I am trying to do is make the program tell the user how many guesses/attempts they have made before getting the correct answer.
This is what I have done so far
class Program
{
public static int correct_answer, counter, user_answer, counterUpdated;
static void Main(string[] args)
{
correct_answer = 4;
do
{
counter = 1;
counterUpdated = counter++;
Console.WriteLine("2+2= ?");
user_answer = Convert.ToInt32(Console.ReadLine());
if (user_answer != correct_answer)
{
Console.Clear();
Console.WriteLine("Wrong, try againg" + " this is your " + counterUpdated + " try.");
}
} while (user_answer != correct_answer); // The code will keep looping until the user prompts the correct answer
Console.Clear();
Console.WriteLine("Well Done! you did it in this amount of guesses " + counterUpdated);
Console.ReadLine();
}
}
If someone could tell me how to make the counter thing work, that would be great.
You always set counter to 1 at the start of the loop, then immediately counterUpdated = counter++; (which is a bit odd anyway...).
Just do it with one counter that you initialize outside the loop and increment inside the loop.
int guessNumber = 0;
do {
guessNumber++;
// ...
Tweaked a bit, and this should work :)
class Program
{
public static int correct_answer, counter, user_answer;
static void Main(string[] args)
{
correct_answer = 4;
counter = 0;
do
{
counter++;
Console.WriteLine("2+2= ?");
user_answer = Convert.ToInt32(Console.ReadLine());
if (user_answer != correct_answer)
{
Console.Clear();
Console.WriteLine("Wrong, try againg" + " this is your " + counter+ " try.");
}
} while (user_answer != correct_answer); // The code will keep looping until the user prompts the correct answer
Console.Clear();
Console.WriteLine("Well Done! you did it in this amount of guesses " + counter);
Console.ReadLine();
}
}
What i did was i removed the counterUpdated variable and had the counter variable do all the counting work :)
Hope it helped :)
Related
Fixed, but now it automatically presses enter when it gets to the Main(); thing and I can't actually input anything in time. Anyone know what's wrong?
using System;
using System.Linq;
namespace Bruh
{
class Program
{
static void Main()
{
int pog = 0;
int pog2 = 0;
Random r = new Random();
Console.WriteLine("Input a whole number");
string poggers = Console.ReadLine();
if (int.TryParse(poggers, out pog))
{
pog = int.Parse(poggers);
}
else
{
Console.WriteLine("ERROR: Not a number. Please input a number and not letters.");
Console.Read();
System.Environment.Exit(1);
}
Console.WriteLine("Input a number higher than the previous");
string poggers2 = Console.ReadLine();
if (int.TryParse(poggers2, out pog2))
{
pog2 = int.Parse(poggers2);
}
else
{
Console.WriteLine("ERROR: Not a number. Please input a number and not letters.");
Console.Read();
System.Environment.Exit(1);
}
int genRand = r.Next(pog, pog2);
Console.WriteLine("This number was randomly generated between " + pog + " and " + pog2 + " and we got: " + genRand);
Console.Read();
Console.WriteLine("Would you like to try again? Y/N");
ConsoleKeyInfo answer = Console.ReadKey();
if (answer.KeyChar == 'y' || answer.KeyChar == 'Y')
{
Console.WriteLine("\n");
Main();
}
else if (answer.KeyChar == 'n' || answer.KeyChar == 'N')
{
System.Environment.Exit(1);
}
else
{
Console.WriteLine("ERROR: Y/N not any other character");
Console.Read();
System.Environment.Exit(1);
}
}
}
}
I've reworked your code into something that is more C#-like :-) - find this below.
Highlights:
You use int.TryParse() correctly, but do the conversion again
inside the true code block, using int.Parse().
No need to call System.Environment.Exit(1); to terminate the program, just let it end.
The call main() is actually a recursive call - where a method (function) calls it self. Usable sometimes, but i often leads to a StackOverflow exception. In this case, you get some strange behaviour...
using System;
namespace Bruh2
{
class Program
{
static void Main()
{
bool tryAgain = true;
while (tryAgain)
{
int pog = 0;
int pog2 = 0;
Random r = new Random();
Console.Write("Input a whole number: ");
string poggers = Console.ReadLine();
while (!int.TryParse(poggers, out pog))
{
Console.WriteLine("ERROR: Not a number. Please input a number and not letters.");
poggers = Console.ReadLine();
}
Console.Write("Input a number higher than the previous: ");
string poggers2 = Console.ReadLine();
while (!int.TryParse(poggers2, out pog2))
{
Console.WriteLine("ERROR: Not a number. Please input a number and not letters.");
poggers2 = Console.ReadLine();
}
int genRand = r.Next(pog, pog2);
Console.WriteLine("This number was randomly generated between " + pog + " and " + pog2 + " and we got: " + genRand);
Console.WriteLine();
Console.WriteLine("Would you like to try again? Y/N");
//ConsoleKeyInfo answer = Console.ReadKey();
string answer = Console.ReadKey().KeyChar.ToString().ToLower();
while (answer!="y" && answer!="n")
{
Console.WriteLine("ERROR: Y/N not any other character");
answer = Console.ReadKey().ToString().ToLower();
}
if (answer == "n")
{
tryAgain = false; // terminate the loop (and thereby the program)
}
}
}
}
}
sorry if this is a repeat question or sounds pretty stupid, but I'm really new to c# and looked throughout the forum and couldn't find anything that I could actually understand.
So I'm trying to write a simple program where the user tries to guess a number between 1 and 25. Everything works except that each run of the loop instead of updating the score from the last run of the loop, like 0+1=1, 1+1=2, 2+1=3, each time it adds 1 to 0. Here is my code. How do I fix this? Thank you!
int score = 0;
int add = 1;
while (add == 1)
{
Console.WriteLine("Guess A Number Between 1 and 25");
string input = Console.ReadLine();
if (input == "18")
{
Console.WriteLine("You Did It!");
Console.WriteLine("Not Bad! Your Score was " + score + add);
break;
}
else
{
Console.WriteLine("Try Again. Score: " + score + add);
}
}
You need to actually add add to score. Try something like this:
int score = 0;
int add = 1;
while (add == 1)
{
Console.WriteLine("Guess A Number Between 1 and 25");
string input = Console.ReadLine();
score += add; // add `add` to `score`. This is the same as `score = score + add;`
if (input == "18")
{
Console.WriteLine("You Did It!");
Console.WriteLine("Not Bad! Your Score was " + score);
break;
}
else
{
Console.WriteLine("Try Again. Score: " + score);
}
}
I've just started learning C# and I'm trying to figure out threads.
So, I've made a two threads and I would like to stop one of them by pressing x.
So far when I press x it only shows on the console but it doesn't abort the thread.
I'm obviously doing something wronng so can someone please point out what I'm doing wrong? Thank you.
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
//Creating Threads
Thread t1 = new Thread(Method1)
{
Name = "Thread1"
};
Thread t4 = new Thread(Method4)
{
Name = "Thread4"
};
t1.Start();
t4.Start();
Console.WriteLine("Method4 has started. Press x to stop it. You have 5 SECONDS!!!");
var input = Console.ReadKey();
string input2 = input.Key.ToString();
Console.ReadKey();
if (input2 == "x")
{
t4.Abort();
Console.WriteLine("SUCCESS! You have stoped Thread4! Congrats.");
};
Console.Read();
}
static void Method1()
{
Console.WriteLine("Method1 Started using " + Thread.CurrentThread.Name);
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Method1: " + i);
System.Threading.Thread.Sleep(1000);
}
Console.WriteLine("Method1 Ended using " + Thread.CurrentThread.Name);
}
static void Method4()
{
Console.WriteLine("Method4 Started using " + Thread.CurrentThread.Name);
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Method4: " + i);
System.Threading.Thread.Sleep(1000);
}
Console.WriteLine("Method4 Ended using " + Thread.CurrentThread.Name);
}
It looks like you have a extra Console.ReadKey(); before if (input2 == "x"), that extra read causes the program to stop and wait before going inside your if statement waiting for a 2nd key to be pressed.
Also input.Key returns a enum, when you do the to string on it the enum will use a capital X because that is what it is set to. Either use input.KeyChar.ToString() to convert it to a string or use
var input = Console.ReadKey();
if (input.Key == ConsoleKey.X)
To compare against the enum instead of a string.
I also recommend you read the article "How to debug small programs", debugging is a skill you will need to learn to be able to write more complex programs. Stepping through the code with a debugger you would have seen input2 was equal to X so your if statement was
if ("X" == "x")
which is not true.
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 made a program which has 5 questions, it reads the users answer and lets them know if they were correct or not, if they were incorrect the user is forced to begin the 5 questions again. I added a count increment so that the program can tell the user the number of times it took to complete the quiz and i also added a "questions left" left feature which will tell you how many questions were left. as of now the code is all in one class and not separated into methods and uses the old "go to" loops. How would I go about changing the loops to a more modern code and how would I program it to use more methods for organising it, also the questions left feature works if the user gets every question correct but when the user gets a question wrong and restarts the questions left feature doesn't output the correct number.
here is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace practicePro
{
class Program
{
public static void Main(string[] args)
{
/*----------------------------------------Declaration----------------------------------------- */
string q1, q2, q3, q4, q5;
int questionsLeft;
questionsLeft = 5;
/*----------------------------------------TITLE----------------------------------------- */
Console.WriteLine("Welcome to the Ultimate quiz!");
Console.WriteLine();
/*----------------------------------------QUESTION 1----------------------------------------- */
int count = 0;
start:
count++;
Console.WriteLine("What programming language has a snake as its name" + " questions left: " + questionsLeft );
Console.WriteLine();
q1 = Console.ReadLine();
q1 = q1.ToUpper();
if (q1 == "PYTHON")
{
Console.WriteLine();
Console.WriteLine("Well Done, you may move on to the next question");
questionsLeft--;
}
else
{
Console.WriteLine("Sorry you got the answer wrong, you have to start again");
goto start;
}
Console.WriteLine();
/*----------------------------------------QUESTION 2----------------------------------------- */
Console.WriteLine("What is the age range to qualify for an apprenticeship in the uk? Please type in the following format xx-yy" + " questions left: " + questionsLeft);
Console.WriteLine();
q2 = Console.ReadLine();
if (q2 == "16-24")
{
Console.WriteLine();
Console.WriteLine("Well Done, you may move on to the next question");
questionsLeft--;
}
else
{
Console.WriteLine("Sorry you got the answer wrong, you have to start again");
goto start;
count++;
}
Console.WriteLine();
/*----------------------------------------QUESTION 3----------------------------------------- */
Console.WriteLine("Is HTML a programming language (Yes or No)" + " questions left: " + questionsLeft);
Console.WriteLine();
q3 = Console.ReadLine();
q3 = q3.ToUpper();
if (q3 == "NO")
{
Console.WriteLine();
Console.WriteLine("Well Done, you may move on to the next question");
questionsLeft--;
}
else
{
Console.WriteLine("Sorry you got the answer wrong, you have to start again");
goto start;
count++;
}
Console.WriteLine();
/*----------------------------------------QUESTION 4----------------------------------------- */
Console.WriteLine("In JavaScript, What are the 2 charecters used to symbolise a single line comment?" + " questions left: " + questionsLeft);
Console.WriteLine();
q4 = Console.ReadLine();
if (q4 == "//")
{
Console.WriteLine();
Console.WriteLine("Well Done, you may move on to the next question");
questionsLeft--;
}
else
{
Console.WriteLine("Sorry you got the answer wrong, you have to start again");
goto start;
count++;
}
Console.WriteLine();
/*----------------------------------------QUESTION 5----------------------------------------- */
Console.WriteLine("500 < 600 && 700 < 600");
Console.WriteLine();
Console.WriteLine("Is the above statement true or false ?" + " questions left: " + questionsLeft);
Console.WriteLine();
q5 = Console.ReadLine();
q5 = q5.ToUpper();
if (q5 == "FALSE")
{
Console.WriteLine();
Console.WriteLine("Well Done, you may move on to the next question");
Console.WriteLine();
Console.WriteLine("Congratulations You have passed the quiz!");
questionsLeft--;
}
else
{
Console.WriteLine("Sorry you got the answer wrong, you have to start again");
goto start;
}
Console.WriteLine();
Console.WriteLine("you took " + count + " time(s) to complete the quiz");
}
}
}
You can create a Question class, which will contain a text (question), and the right answer.
In your Main method, you can create and initialize the list of questions :
List<Question> questions = new List<Question>() {
new Question("What programming language has a snake as its name ?", "PYTHON"),
new Question(...),
...
}
Then you can create your workflow algorithm. Example :
Console.WriteLine("Welcome to the Ultimate quiz!");
Console.WriteLine();
int count = 0;
while(questions.Count > 0) {
Console.WriteLine(question.First().Text + " (question left: " + questions.Count + ")");
string answer = Console.ReadLine();
if (answer == questions.First().Answer)
{
Console.WriteLine();
Console.WriteLine("Well Done, you may move on to the next question");
questions.RemoveAt(0);
}
else
{
Console.WriteLine("Sorry you got the answer wrong, you have to start again");
count++;
}
}
Console.WriteLine();
Console.WriteLine("you took " + count + " time(s) to complete the quiz");
You can even create a Ask() method in the Question class, which will ask the question and analyze the answer (this method must take in parameter the number of question left, to display it).
Writing methods that contain logic is easy:
// Without extra method
class Program
{
static void Main(string[] args)
{
int a = 1;
int b = 2;
int c = a + b;
}
}
would turn into
// With extra method
class Program
{
static void Main(string[] args)
{
int a = 1;
int b = 2;
int c = Add(a, b);
}
static int Add(int num1, num2)
{
return num1 + num2;
}
}
Basics about methods:
They always have an access modifier (public or private, if none is given, it's private in C#
They always have a return type (in this case: int)
They always have a name (in this case: Add)
They can take parameters (in this case: num1 and num2)
If the return type is not void they always need a return statement in every code path
In order to loop until the player has answered every question correctly, you could make the asking method a bool type and as long as it returns false (which should happen every time the player answers wrong), a Player class calls the asking method.
// Quiz being the asking method
while(!Quiz())
{
// wrongAnswers being the counter for failed attempts
wrongAnswers++;
}
Console.WriteLine("Success!");
This will call the Quiz() method, which will then ask the player its 5 questions (which can, as Paul DS stated, be stored in a seperate class) and if it returns false (which means the player has answered one question wrong), it adds 1 to wrongAttempts, before calling it again. If it returns true, wrongAnswers is not incremented by 1 and "Success!" is shown.