Need to get it to loop after the user presses "r" at this part, need it to do as it says in the Console.WriteLine and redo all the questions
if (numOfCorrect > 7)
Console.Clear();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("You got " + numOfCorrect + "correct! Incredible job! Can you do it again though? ");
Console.WriteLine("If you want to retry the quiz press 'r', if you wish to exit the program press 'c'");
if (Console.ReadKey().Key != ConsoleKey.R)
Console.Clear();
using System;
namespace ConsoleApp1
{
class Program
{
static int iNum1;
static int iNum2;
static int numOfCorrect;
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Ten Question Multiplication Quiz");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Instructions");
Console.WriteLine("This program will give you 10 questions on multiplication for you to answer, after answering the ten questions it will display how many you got right!");
Console.WriteLine("If you decide to retry the quiz it will have 10 completely different questions! So be prepared for a challenge.");
Console.ResetColor();
Console.WriteLine("Press Enter to Start");
Console.ReadKey();
Console.Clear();
Random rRandom = new Random();
for (int loop = 0; loop < 10; loop++)
{
int userAnswer;
int answer;
iNum1 = rRandom.Next(11);
iNum2 = rRandom.Next(11);
{
Console.Write("What is " + iNum1 + " times " + iNum2 + "? ");
answer = iNum1 * iNum2;
userAnswer = Convert.ToInt32(Console.ReadLine());
}
if (answer == userAnswer)
{
Console.WriteLine(userAnswer + " is correct ");
numOfCorrect++;
Console.Clear();
}
else
{
Console.WriteLine(userAnswer + " is incorrect ");
Console.Clear();
}
if (userAnswer > 100)
{
loop += (loop - 1);
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("That number is too high, try again");
}
}
{
if (numOfCorrect > 7)
Console.Clear();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("You got " + numOfCorrect + "correct! Incredible job! Can you do it again though? ");
Console.WriteLine("If you want to retry the quiz press 'r', if you wish to exit the program press 'c'");
if (Console.ReadKey().Key != ConsoleKey.R)
Console.Clear();
else if (Console.ReadKey().Key != ConsoleKey.C)
System.Environment.Exit(0);
}
}
}
}
You can either capsulate your whole code inside another loop like pawel stated in his comment. Or you could also create a recursive function call like:
static void Main(string[] args)
{
Quiz();
}
void Quiz(){
// Initialize stuff
// Display stuff
for(int loop = 0; loop < 10; loop++)
{
// Question User
// Evaluate Answers
// and so on
// Check user input for retry
if (Console.ReadKey().Key != ConsoleKey.R)
{
Console.Clear();
Quiz(); // <---- Calls the same method again
}
}
}
Related
I can't ever get guessLimit to equal 1, in the system log when I enter the limit of guesses as 5 and start guessing, the guessLimit will go down all the way to 2 and it will give me the "You Lose" message without letting me do my final guess... is there a reason for that?
public static void Main(string[] args){
string guess = "";
bool outOfguesses = false;
int guessCount = 0;
Console.Clear();
Console.Write("Enter the amount of guesses you want: ");
int guessLimit = Convert.ToInt32(Console.ReadLine());
Console.Clear();
Console.Write("Enter a word that will be guessed...: ");
string secretWord = Console.ReadLine();
Console.Clear();
Console.Write("You have " + guessLimit + " guesses" + "\nEnter a guess: ");
guess = Console.ReadLine();
while(guess.ToLower() != secretWord.ToLower() && !outOfguesses){
if(guessLimit >= guessCount || guessLimit == 1){
guessCount++;
guessLimit--;
Console.Write("\nWRONG! You have " + guessLimit + " guesses left." + "\nEnter another guess: ");
guess = Console.ReadLine();
} else{
outOfguesses = true;
}
}
if(outOfguesses == true){
Console.WriteLine("\nSorry...\nYou lose!");
} else{
Console.WriteLine("\nGood Job.\nYou Win!!");
}
Console.ReadLine();
}
When your if statement reaches
(Is 2 >= 3) this is false so it will skip over the if and go to the else
Which is why it stops there.
Also change your guesslimit ==1 to <1
I'm currently making a C# 2 player Rock paper scissors game and i'm stuck for what to do.
Basically as it stands, the users enter which keys they would like for rock, paper and scissors.
I have these keys stored in variables so the program remembers them. The issue is that I can't find or think of how the program then detects how these keys have been pressed afterwards when the game itself has initiated.
I thought possibly enum's or storing them in an array possibly?
Not sure, Here's what i have so far.
static bool winner = false;
static string player1;
static string player2;
static ConsoleKeyInfo Rock1;
static ConsoleKeyInfo Rock2; //variables for objects and players names etc
static ConsoleKeyInfo Scissors1;
static ConsoleKeyInfo Scissors2;
static ConsoleKeyInfo Paper1;
static ConsoleKeyInfo Paper2;
static void Main(string[] args)
{
do
{
PlayerChoosesNameAndKeys();
game(); //main game loop
} while (winner == false);
}
static public void PlayerChoosesNameAndKeys()
{
for (int i = 1; i <= 2; i++)
{
Console.WriteLine("Player {0} chooses there name:", i);
if (i == 1)
{
player1 = Console.ReadLine(); //players choose names
Console.WriteLine("Player 1's name is: {0}", player1);
}
else
{
player2 = Console.ReadLine();
Console.WriteLine("Player 2's name is: {0}", player2);
}
}
Console.WriteLine("Players now choose the keys they wish to represent the different objects");
for (int i = 0; i <= 5; i++)
{
if (i == 0)
{
Console.WriteLine("{0} choose what key Rock is", player1);
Rock1 = Console.ReadKey();
Console.WriteLine();
Console.WriteLine("Press enter to confirm");
Console.ReadLine();
}
else
{
if (i == 1)
{
Console.WriteLine("{0} choose what key Paper is", player1);
Paper1 = Console.ReadKey();
Console.WriteLine();
Console.WriteLine("Press enter to confirm");
Console.ReadLine();
}
if (i == 2) //selection to decide what keybinds players want
{
Console.WriteLine("{0} choose what Key Sisscors is", player1);
Scissors1 = Console.ReadKey();
Console.WriteLine();
Console.WriteLine("Press enter to confirm");
Console.ReadLine();
}
if (i == 3)
{
Console.WriteLine("{0} choose what key Rock is", player2);
Rock2 = Console.ReadKey();
Console.WriteLine();
Console.WriteLine("Press enter to confirm");
Console.ReadLine();
}
if (i == 4)
{
Console.WriteLine("{0} choose what key Paper is", player2);
Paper2 = Console.ReadKey();
Console.WriteLine();
Console.WriteLine("Press enter to confirm");
Console.ReadLine();
}
if (i == 5)
{
Console.WriteLine("{0} choose what Key Sisscors is", player2);
Scissors2 = Console.ReadKey();
Console.WriteLine();
Console.WriteLine("Press enter to confirm");
Console.ReadLine();
}
}
}
static public void game()
{
int score1 = 0;
int score2 = 0;
int count = 1;
//actual game
do
{
Console.WriteLine("Round {0}", count);
Console.WriteLine("Rock...");
Console.WriteLine("Paper...");
Console.WriteLine("Scissors...");
Console.WriteLine("{0} input Object!: ",player1);
ConsoleKeyInfo input = Console.ReadKey();
Console.WriteLine();
if (input.Key == ConsoleKey.Rock1)
{
}
} while (score1 != 10 || score2 != 10);
}
You can simply save user choices as character (for example char Rock); and then use ConsoleKeyInfo.KeyChar:
if (input.KeyChar == Rock)
{
}
for example:
char Rock = 'r'; // default value
Console.WriteLine("{0} choose what key Rock is", player1);
Rock = Console.ReadKey().KeyChar;
Or just check the insterted key with your saved key:
Console.WriteLine("{0} choose what key Rock is", player1);
ConsoleKeyInfo Rock = Console.ReadKey();
and then:
ConsoleKeyInfo input = Console.ReadKey();
if (input.Key == Rock.Key)
{
}
I need to know how to go back to the start of a cmd app (like when I start the app) Here is what I have:
using System;
namespace Convo-
{
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.BackgroundColor = ConsoleColor.DarkBlue;
Console.WriteLine("Friend- How is your day going?");
Console.WriteLine(" ");
Console.WriteLine("You- Good = 1" +
" / Bad = 2");
ConsoleKeyInfo keyinfo = Console.ReadKey();
if (keyinfo.KeyChar == '1')
{
Console.WriteLine(" ");
Console.WriteLine("Friend- That's very nice!");
}
else
{
Console.WriteLine(" ");
Console.WriteLine("Friend- Im sorry is there anything I can do?");
}
Console.WriteLine(" ");
Console.WriteLine("(Don't like your choice go back by clicking 3)");
bool running = true;
if (keyinfo.KeyChar == '3')
{
//here is where i need the go back function
}
}
}
}
One of the most basic units of re-use in programming is the function.
By placing the code within a function, we can call it again easily (the example below shows the function calling itself, which re-starts the conversation).
using System;
namespace Convo-
{
class Program
{
static void Main(string[] args)
{
StartConversation();
}
private static void StartConversation()
{
Console.ForegroundColor = ConsoleColor.Red;
Console.BackgroundColor = ConsoleColor.DarkBlue;
Console.WriteLine("Friend- How is your day going?");
Console.WriteLine(" ");
Console.WriteLine("You- Good = 1" +
" / Bad = 2");
ConsoleKeyInfo keyinfo = Console.ReadKey();
if (keyinfo.KeyChar == '1')
{
Console.WriteLine(" ");
Console.WriteLine("Friend- That's very nice!");
}
else
{
Console.WriteLine(" ");
Console.WriteLine("Friend- Im sorry is there anything I can do?");
}
Console.WriteLine(" ");
Console.WriteLine("(Don't like your choice go back by clicking 3)");
bool running = true;
if (keyinfo.KeyChar == '3')
{
//here is where i need the go back function
StartConversation();
}
}
}
}
And to add some additional clarity, I have deliberately undertaken "one single move" in the game of chess that is...
Extract 'til you drop
Which means you need to continue to refactor out methods that have a single responsibility to make your code more readable.
Couldn't find any other answer on the site that covers this. If else is run and an error message is displayed, is it possible to restart the program by looping back to the start instead of restarting the console?
class Program
{
static void Main(string[] args)
{
int User;
int Array;
StreamWriter outfile = new StreamWriter("C://log.txt");
Console.WriteLine("Input an number between 1 and 100");
User = Convert.ToInt32(Console.ReadLine());
if (User < 101 && User > 0)
{
for (Array = 1; Array <= User; Array++)
{
Console.WriteLine(Array + ", " + Array * 10 * Array);
outfile.WriteLine(Array + ", " + Array * 10 * Array);
}
{
Console.WriteLine("Press Enter To Exit The Console");
outfile.Close();
Console.ReadLine();
}
}
else
{
Console.WriteLine("Sorry you input an invalid number. ");
Console.ReadLine();
}
}
}
Sorry! To be more clear I need to make the Program start again if the user inputs an invalid number
Thanks for the help!
You can do this instead
User = Convert.ToInt32(Console.ReadLine());
while (User >= 101 || User <= 0)
{
Console.WriteLine("Sorry you input an invalid number. ");
User = Convert.ToInt32(Console.ReadLine());
}
An easy way of doing this is placing your code inside a while loop, so that the code keeps repeating. The only way to exit the loop would be for the condition you just set in the if clause to be true. So something along the lines of:
class Program
{
static void Main(string[] args)
{
int User;
int Array;
bool isUserWrong = true; //This is a flag that we will use to control the flow of the loop
StreamWriter outfile = new StreamWriter("C://log.txt");
while(isUserWrong)
{
Console.WriteLine("Input an number between 1 and 100");
User = Convert.ToInt32(Console.ReadLine());
if (User < 101 && User > 0)
{
for (Array = 1; Array <= User; Array++)
{
Console.WriteLine(Array + ", " + Array * 10 * Array);
outfile.WriteLine(Array + ", " + Array * 10 * Array);
}
isUserWrong = false; // We signal that we may now leave the loop
}
else
{
Console.WriteLine("Sorry you input an invalid number. ");
Console.ReadLine();
//Note that here we keep the value of the flag 'true' so the loop continues
}
}
Console.WriteLine("Press Enter To Exit The Console");
outfile.Close();
Console.ReadLine();
}
}
I'm making a program that has little programs inside of it, and I've come to a dilemma. On my first mini-program which rearranges digits to find the greatest possible number from those digits, it asks if the user wants to quit. If they respond "Yes" then the function returns 0 which is evaluated in the main(string[] args) method. My problem is that whenever the user says "No", the mini-program still doesn't continue. Here's my source:
namespace ACSL_Competition
{
class Program
{
static int DigitRearranger()
{
string[] mainString = {};
Console.WriteLine("---------Welcome to the Digit Re-arranger!---------");
Console.WriteLine("I take a positive number up to 10000, and find the highest number that can be made out of its digits.");
Console.WriteLine("Instructions: Enter a number up to 10000, and see the results!");
drLabel:
Console.Write("Your Number: ");
string input = Console.ReadLine();
int inputNumber = 0;
try { inputNumber = int.Parse(input); }
catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message); goto drLabel; }
/*Placeholder code for the moment*/Console.WriteLine(inputNumber.ToString());
evaluate:
Console.Write("Do you want to exit? Yes/No: ");
if (Console.ReadLine().Equals("Yes"))
return 1;
else if (Console.ReadLine().Equals("No"))
{
goto drLabel;
}
else
{
return 1;
}
}
static void Main(string[] args)
{
Console.WriteLine("Welcome to the ACSL Competition Program. Choose a program to begin:");
Console.Write("\n\t");
Console.WriteLine("1\tDigit Re-arranger");
label:
Console.Write("\nProgram: ");
string input = Console.ReadLine();
int number = 0;
try { number = int.Parse(input); }
catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message); goto label; }
if (number == 1)
{
Console.WriteLine("\n");
if (DigitRearranger() == 1)
{
goto label;
}
else if (DigitRearranger() != 1)
{
DigitRearranger();
}
}
else if (!number.Equals(1))
{
Console.WriteLine("Not a valid program.");
goto label;
}
//----------------
Console.ReadLine();
}
}
}
The underlying problem is that you're calling readline twice. The first time it gets the entered value, i.e. Yes, the second time you call it there is no data to read so it returns "". If you need to reuse the same input store it in a variable, i.e.
string inputVal = Console.ReadLine();
I hate goto statements, maybe you could restructure your code in to a while loop, something like:
bool exit = false;
while(!exit)
{
Console.Write("Your Number: ");
//Your main code
Console.Write("Do you want to exit? Yes/No: ");
if(Console.ReadLine() != "No")
exit = true;
}
In fact, you could get rid of the exit variable, just do while(true) and return if the user enters anything other than no.
I have a few suggestions:
Write your code to be more modular to improve readability. The Main() method should only drive the outer UI loop, each module provides its own UI.
Never use goto statements.
Don't use Console.Readline() inside an if condition (when not "Yes", it was called twice).
Here is my refactored version of your code:
class Program {
static void DigitRearranger()
{
string response = "";
int num;
do
{
Console.Clear();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("---------Welcome to the Digit Re-arranger!---------");
Console.WriteLine("I take a positive number up to 10000, and find the highest number that can be made out of its digits.");
Console.WriteLine("Instructions: Enter a number up to 10000, and see the results!");
Console.ResetColor();
Console.Write("Your Number: ");
if (!int.TryParse(Console.ReadLine(), out num))
{
Console.WriteLine("Not a number. Press any key to continue");
Console.ReadKey();
continue;
}
//todo: reaarrange the number & print results
/*Placeholder code for the moment*/
Console.WriteLine(num);
Console.Write("Do you want to exit? Yes/No: ");
response = Console.ReadLine();
} while (response.ToLower() != "yes");
}
//UI driver only in Main method:
static void Main(){
string response = "";
do
{
Console.Clear();
Console.WriteLine("Welcome to the ACSL Competition Program. Choose a program to begin:");
Console.WriteLine("\n\t1\tDigit Re-arranger");
Console.WriteLine("\tq\tQuit");
Console.Write("\nProgram: ");
response = Console.ReadLine();
switch(response)
{
case "1":
DigitRearranger();
break;
case "q":
break;
default:
Console.WriteLine("Not a valid program. Press any key to continue");
Console.ReadKey();
break;
}
} while (response.ToLower() != "q");
Console.ReadLine();
}}