Organising code into methods and classes - c#

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.

Related

Adding value to int variable each run of the loop

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);
}
}

console application where the user has 5 tries to guess number between 1 and 100

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

What is exactly causing my main method to run infinitely when instead I want it to run my method incrementally based off the user's response?

I'm trying to write a beginner program, where I roll 2 dies, and it tests the dies, if there's any evens it will say "evens are better then odds" and if there's a scenario where there's only odds it will say, "Odds are still cool", and after each roll it will ask the user if they want to play again, if not it will tell the user how many times they rolled the die. When I run the program, it will run, and ask the user if they want to roll again, when I type "YES" it runs infinitely. I don't know if the problem has to do with how my main method is written or if it's the TinasDice method.
I've tried going about using only the if/else statement in the main method where the user's input is tested, but that immediately exits out of the program.
TinasDice();
Console.WriteLine("Do you want to play again?");
string answer;
int counter = 0;
answer = Console.ReadLine();
while (answer == "YES")
{
if (answer == "YES")
{
TinasDice();
}
else
{
Console.WriteLine("The number of times the dice was die was thrown is: " + counter);
Console.WriteLine("Nice game!");
Console.WriteLine("Thanks for playing. Come play again soon!");
}
}
}
public static void TinasDice()
{
Random random = new Random();
int dice1 = new int();
int dice2 = new int();
dice1 = random.Next(1, 6);
dice2 = random.Next(1, 6);
Console.WriteLine("Hey Welcome to Tina's Dice Game.");
Console.WriteLine("Let's start!");
if (dice1 % 2 == 0 || dice2 % 2 == 0)
{
Console.WriteLine("I got " + dice1 + " and " + dice2);
Console.WriteLine("Evens are better then odds!");
}
else
{
Console.WriteLine("I got a " + dice1 + " and " + dice2);
Console.WriteLine("Odds ares still cool!");
}
I'm just trying to get the program to run incrementally after TinasDice is ran the first time, so when the user types "YES" it will run TinasDice once, and then prompt the user again, until the user types something else other then "YES".
Taking your example from above.
TinasDice();
Console.WriteLine("Do you want to play again?");
string answer = "YES";
int counter = 0;
while (answer == "YES")
{
answer = Console.ReadLine();
counter++;
if (answer == "YES")
{
TinasDice();
}
else
{
Console.WriteLine("The number of times the dice was die was thrown is: " + counter);
Console.WriteLine("Nice game!");
Console.WriteLine("Thanks for playing. Come play again soon!");
break;
}
}
}
Note the defaulting of the "YES" and the break

Do... While loop counter implementation not working

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 :)

how to display a variable in console c#

I'm trying to create a simple console game where you take care of yourself by feeding yourself.
using System;
namespace Project1
{
static class Program
{
static void Main(string[] args)
{
int hunger = 100;
Console.WriteLine("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine("Good choice, " + name);
Console.WriteLine("Press SPACE to continue");
while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Spacebar))
{
// do something
int h = hunger - 2;
}
Console.WriteLine("You are hungry," + name);
Console.WriteLine("Press F to feed");
while (!(Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.F))
{
// do something
int food = hunger;
}
}
}
}
How can I display the current hunger after a change is made too it? I want to display the food level so the player knows to feed it and does not accidentally over feed it. By any chance is there a way to go back to a earlier line so I don't need to copy and paste the thing forever and ever? Thanks.
It looks like this will be very broad to answer properly, so I'm going to leave it pretty abstract. You need to put reusable logic in methods. You need a "game loop" or "input loop". You need to learn about variables and passing them into methods.
You also may want to introduce a Player class as opposed to various variables to hold separate values.
Your game loop may look like this:
ConsoleKey input = null;
do
{
var player = DoGameLogic(input, player);
PrintGameInfo(player);
input = ReadInput(player);
}
while (input != ConsoleKey.Q)
When you got all this in order and you want to make the output look nice, take a look at Writing string at the same position using Console.Write in C# 2.0, Advanced Console IO in .NET.
You can modify the position of the cursor with Console.CursorLeft and Console.CursorTop and overwrite previous values.
Cursor.Left = 0;
Console.Write("Hunger: {0:0.00}", hunger);
EDIT: AS mentioned by "CodeMaster", you can do:
Console.Write("Test {0:0.0}".PadRight(20), hunger);
To make sure you have overwritten the previous data if it differs in length.
is this something you wanted to achieve:-
static void Main(string[] args)
{
const int MAX_FEED_LEVEL = 3; //configure it as per your need
const int HIGHEST_HUNGER_LEVEL = 0; //0 indicates the Extreme hunger
int hunger = MAX_FEED_LEVEL, foodLevel = HIGHEST_HUNGER_LEVEL;
string name = string.Empty;
char finalChoice = 'N', feedChoice = 'N';
Console.Write("Enter your name: ");
name = Console.ReadLine();
Console.Write("Good choice, {0}!", name);
Console.WriteLine();
do
{
Console.WriteLine();
Console.WriteLine("current hunger level : {0}", hunger);
if (hunger > 0)
Console.WriteLine("You are hungry, {0}", name);
Console.Write("Press F to feed : ");
feedChoice = (char)Console.ReadKey(true).Key;
if (feedChoice == 'F' || feedChoice == 'f')
{
if (foodLevel <= MAX_FEED_LEVEL && hunger > HIGHEST_HUNGER_LEVEL)
{
hunger = hunger - 1; //decrementing hunger by 1 units
foodLevel += 1; //incrementing food level
Console.WriteLine();
Console.WriteLine("Feeded!");
Console.WriteLine("Current Food Level : {0}", foodLevel);
}
else
{
Console.WriteLine();
Console.WriteLine("Well Done! {0} you're no more hungry!", name);
goto END_OF_PLAY;
}
}
else
{
Console.Clear();
Console.WriteLine();
Console.Write("You chose not to feed !");
}
Console.WriteLine();
Console.Write("want to continue the game ? (Y(YES) N(NO))");
finalChoice = (char)Console.ReadKey(true).Key;
} while (finalChoice == 'Y' || finalChoice == 'y');
END_OF_PLAY:
Console.WriteLine();
Console.Write("===GAME OVER===");
Console.ReadKey();
}

Categories