Right now my problem is getting choice 2 to save and rewrite what was written in choice 1.
Choice 3 should then reset everything.
Right now i tried with at if inside an if and still not getting it to work.
while (true)
{
Console.WriteLine("\tWelcome to my program"); // Makes the user select a choice
Console.WriteLine("[1] To write");
Console.WriteLine("[2] To see what you wrote");
Console.WriteLine("[3] Reset");
Console.WriteLine("[4] End");
string choice = Console.ReadLine();
string typed = ("");
if (choice == "1") // If 1 program asks for text
{
Console.WriteLine("Thank you for your choice, input text");
typed = Console.ReadLine();
}
else if (choice == "2") // Is supposed to say "You wrote, and what user wrote"
{
Console.WriteLine(typed);
}
else if (choice == "3") // Resets the text so if 2 is selected it would say "You wrote, "
{
Console.WriteLine("Reset. Would you like to try again?");
typed = "";
}
else if (choice == "4") // Ends program
{
break;
}
else
{
Console.WriteLine("Input not computing, try again");
}
Your issue is as follows.
First, you are looping your entire program through a while (true) loop. Once the user choice is made, the program will go back to the while (true). Note also that string typed is defined inside the loop. Therefore, every time the loop is called (which is every choice made), the program resets the value of 'typed'.
To fix this, introduce string typed outside the loop.
string typed = "";
while (true)
{
//choices and stuff goes back here
}
Edit: I noticed this comment of yours //Is supposed to say "You wrote, and what user wrote on choice 2. Note that your code in choice 2 won't output "You wrote" + typed. To correct that, change Console.WriteLine(typed); to Console.WriteLine("You wrote, " + typed);.
Related
I was trying to make a text adventure in C#. Ive only been coding for a few days and I can't find how to do this.
I was trying to to ask a yes or no question and yes would go to the next question in the story. If its a no I wanted it to start a loop till it forces the player to type the correct answer (yes). After the user types yes how do i get it to exit the loop and move to the next part of the story? If this doesn't make sense ask me and I will try to reexplain.
Here is how i got it to at least go to the next section. I would like it to loop till the user says yes. I would like it to loop though.
using System;
namespace Game.of.words.forgotten.period
{
class Program
{
public static player currentplayer = new player();
static void Main(string[] args)
{
Console.Clear();
Start();
Encounters.Firstencounter();
}
static void Start()
{
Console.WriteLine("Game Of Words The Forgotten Period");
Console.WriteLine("Welcome to my world. What is your name? ");
string currentplayer = Console.ReadLine();
Console.Clear();
Console.WriteLine("We are happy to see you here " + currentplayer + " !");
Console.WriteLine("I bet you are wondering where you are and why you are here. Is that correct? (Yes) or (No)");
string input = Console.ReadLine();
if (input.ToLower() == "yes")
{
//Yes
Console.WriteLine("I thought as much.I am incredibly skilled at the confusion arts");
}
else
{
//no
Console.WriteLine("Well I just assumed because... I mean I took all this time to make this a crazy experience to");
Console.WriteLine(" confuse you but I guess you are too smart for that.");
Console.WriteLine("Please just say yes.");
Console.ReadLine();
if (input.ToLower() == "no")
{
Console.WriteLine("Okay fine. You can be like that");
}
else
Console.Write("I thought as much. I am incredibly skilled at the confusion arts.");
Console.ReadKey();
Console.Clear();
}
Console.ReadLine();
Console.WriteLine("As you see we are in the middle of no where. Surounded by Tall mountains and no trees.");
Console.WriteLine("I bet you can feel the slight breeze and smell the fragrece of the flowers all around us");
Console.WriteLine("Do you want me to telaport us into town or do you walk through the flowers and watch the clouds for a while? ");
Console.ReadLine();
Console.Clear();
}
}
}
Here is another example. I am not understanding something.
class Program
{
static void Main(string[] args)
{
Console.Write("hello Player what is your name? ");
String Name= Console.ReadLine();
string j = ("June");
if (Name != j)
{
Console.WriteLine("Hello " + Name);
while (Name != j)
{
Console.WriteLine("Thats not your name");
// Creates endless loop. If I add a readline it will
//print hello michael and then that is not your name will
//Repeat on every enter.
//If I put a break; it just prints both and ends.
}
Console.ReadLine();
}
Console.ReadLine();
}
}
on the second example you don't really need the if statement, you can use the while loop.
string exitName = "exit";
Console.Write($"hello Player what is your name? (to skip the while loop you must type {exitName}) {Environment.NewLine}");
String Name = Console.ReadLine();
while (Name != exitName)//while the name does not equal 'exit' you will stay in the loop
{
Console.WriteLine("You did not exit!");
Console.WriteLine($"You entered {Name} you must enter {exitName} to exit this loop!");
Name = Console.ReadLine();
}
Console.WriteLine("press any key to end game");
Console.ReadLine();
In your first example you have the lines
Console.WriteLine("Please just say yes.");
Console.ReadLine();
this should be
Console.WriteLine("Please just say yes.");
input = Console.ReadLine();
otherwise you aren't assigning anything to input again.
I'm a newbie and as an exercise, have to create an application that will allow the user 3 attempts to enter their pin correctly. The issue I am having is that once the correct pin is entered, the application shuts down. The same happens after the third attempt. So the "Correct Pin" and "Goodbye" don't actually print out first. Here's what I have at the moment. Thanks.
int pin = 2456;
int attempts = 1;
bool correctPin = false;
while (attempts <= 3 && correctPin == false)
{
//Ask user to enter pin
Console.WriteLine("Please enter your pin");
//read what user types
string guess = Console.ReadLine();
int number1 = int.Parse(guess);
attempts++;
//if correct pin entered
if (number1 == pin)
{
correctPin = true;
Console.WriteLine("Correct Pin");
}
//if incorrect pin entered
else if (number1 != pin)
{
Console.WriteLine("Incorrect Pin");
}
else if (attempts > 3)
{
Console.WriteLine("Goodbye");
}
}
}
}
}
Outside the loop you can put a:
Console.ReadLine();
statement to prevent the program from exiting
It would be good, however, to at least give the user a clue that the application is waiting by writing something like "Press Enter to Exit..." to the console
The console window is closing since there is nothing else left to do. You should put Console.Readline() at the end.
Also, you should put Console.WriteLine("Goodbye"); out of the if statement, just above the Readline().
In my C# code (I am currently trying to learn it), I am trying to make a text - console based adventure game. The first 'Section' works, and I copy pasted it over to and changed the name of the variables etc. (Its a repetitive code), but it just wont work.
Here is the code:
using System;
namespace LearningC
{
class MainClass
{
public static void Main (string[] args)
{
lvl_1_start: //LEVEL ONE
Console.WriteLine ("Welcome to AlexAdventureLand.\nPlease press the enter key to start.");
Console.ReadKey ();
Console.WriteLine ("You are a rabbit in a burrow. There is a badger outside. \nPress 1 to leave the burrow. \nPress 2 to wait.");
int lvl_1 = Convert.ToInt32 (Console.ReadLine ());
if (lvl_1 == 1) {
Console.WriteLine ("The badger sees you and eats you. \nYou fail. \n\nPress enter to try again.");
Console.ReadKey ();
goto lvl_1_start;
} else if (lvl_1 == 2) {
Console.WriteLine ("The badger scurries away!");
goto lvl_2_start;
} else {
Console.WriteLine ("You pressed the wrong button. Start again.");
goto lvl_1_start;
}
lvl_2_start: //LEVEL TWO
Console.WriteLine ("Now what do you want to do? \nPress 1 to leave burrow. \nPress 2 to wait.");
Console.ReadKey ();
int lvl_2 = Convert.ToInt32 (Console.Read ());
if (lvl_2 == 1) {
Console.WriteLine ("You leave the burrow and look around.");
Console.ReadKey ();
goto lvl_3_prt_a_start;
} else if (lvl_2 == 2) {
Console.WriteLine ("You wait a little longer. \nYou can hear footsteps around your burrow. You wonder whether it's your friend - troy - or the badger still.");
goto lvl_3_prt_b_start;
} else {
Console.WriteLine ("You pressed the wrong button. Start again.");
goto lvl_2_start;
}
lvl_3_prt_a_start: //LEVEL THREE PART A
Console.WriteLine ("PlaceHolder");
Console.ReadKey ();
lvl_3_prt_b_start:
Console.WriteLine ("PlaceHolder");
Console.ReadKey ();
}
}
}
The problem occurs when running it. The first section works fine, and pressing '1', '2' or any other number works - but on section two, it always comes up with the else section, none of the if or if else clauses. Any quick help would be great. Thanks!
The problem is that you're calling both ReadKey and Read. These each read a single character, so ReadKey gets your selection, and Read just gets your \r (first character of newline). ReadKey returns info about your keypress (which is ignored), and Read returns an int corresponding to the char value you entered (note that int and char are numeric types, and converting one of those ToInt32 is different from parsing a string!).
You should use code like your working code to read input:
int lvl_2 = Convert.ToInt32(Console.ReadLine()); // or, does the same thing:
int lvl_2 = int.Parse(Console.ReadLine());
(the Convert class supports conversions in a wide range of types; if all you need to do is parse a string to an int, int.Parse is the more common option and gives you more choices)
Also, you should avoid gotos in C#. They lend themselves to writing spaghetti code, and overall are a bad idea (except for very rare exceptions). I can see that they're already leading to your method being a God Method. Here's an example that should put you more on the right track:
static void Main(string[] args)
{
Level1();
}
static void Level1()
{
Console.WriteLine("Welcome to AlexAdventureLand.\nPlease press the enter key to start.");
Console.ReadKey();
Console.WriteLine("You are a rabbit in a burrow. There is a badger outside. \nPress 1 to leave the burrow. \nPress 2 to wait.");
int selection = int.Parse(Console.ReadLine());
if (selection == 1)
{
Console.WriteLine("The badger sees you and eats you. \nYou fail. \n\nPress enter to try again.");
Console.ReadKey();
Level1();
}
else if (selection == 2)
{
Console.WriteLine("The badger scurries away!");
Level2();
}
else
{
Console.WriteLine("You pressed the wrong button. Start again.");
Level1();
}
}
static void Level2()
{
Console.WriteLine("Now what do you want to do? \nPress 1 to leave burrow. \nPress 2 to wait.");
int selection = int.Parse(Console.ReadLine());
if (selection == 1)
{
Console.WriteLine("You leave the burrow and look around.");
Console.ReadKey();
Level3A();
}
else if (selection == 2)
{
Console.WriteLine("You wait a little longer. \nYou can hear footsteps around your burrow. You wonder whether it's your friend - troy - or the badger still.");
Level3B();
}
else
{
Console.WriteLine("You pressed the wrong button. Start again.");
Level2();
}
}
static void Level3A()
{
Console.WriteLine("PlaceHolder");
Console.ReadKey();
}
static void Level3B()
{
Console.WriteLine("PlaceHolder");
Console.ReadKey();
}
I am working on a program that functions like a quiz. Although I am having issues right now with not allowing the user to simply hit 'Enter' without typing in a guess and proceeding to the next question.
I am trying two different ways of doing it, the first way is using a try and catch block, but I am having issues understanding how that works exactly. I have tried looking up the correct syntax for try and catch blocks and tried including breaks and continue within, though I would get an error message that read "No enclosing loop out of which to break or continue"
public void Play()
{
DisplayWelcome();
Console.WriteLine("First Question:");
Console.WriteLine("---------------");
Console.WriteLine(entertainmentquestions[0]);
guess = Console.ReadLine();
try
{
if (guess == entertainmentanswers[0])
{
Console.WriteLine("You got it right!");
Console.WriteLine("Press 'Enter' when you are ready to see the next question");
Console.ReadLine();
Console.Clear();
}
else
{
Console.WriteLine("You got this one wrong! Better luck next one");
Console.WriteLine("Press 'Enter' when you are ready to see the next question");
Console.ReadLine();
Console.Clear();
}
break;
}
catch
{
Console.WriteLine("Incorrect input, please enter a valid answer");
continue;
}
The second way I've thought it could be done would be through an if statement but I don't know how I could re-prompt the user after their hitting enter has been displayed as 'invalid'
public void Play()
{
DisplayWelcome();
Console.WriteLine();
Console.WriteLine("First Question:");
Console.WriteLine("---------------");
Console.WriteLine(hstryquestions[0]);
guess = Console.ReadLine().ToUpper();
if (guess != "")
{
if (guess == hstryanswers[0])
{
Console.WriteLine();
Console.WriteLine("You got it right!");
Console.WriteLine("Press 'Enter' when you are ready to see the next question");
Console.ReadLine();
Console.Clear();
}
else
{
Console.WriteLine();
Console.WriteLine("You got this one wrong! Better luck next one");
Console.WriteLine("Press 'Enter' when you are ready to see the next question");
Console.ReadLine();
Console.Clear();
}
}
else if (guess == "")
{
Console.WriteLine("Please enter a valid answer");
Console.ReadLine();
}
Any help would be greatly appreciated, I am struggling with finding the answer to this online and in the C# books I have. Perhaps is could be I just don't know what exactly to look for..
Trying using a loop! Perhaps a do-while loop!
Something like this:
do{
ask for input
get input
}while(input is not valid)
This kind of loop will repeatedly get user input until the input passes some validity test that you define. Here's a tutorial on do while loops in C#: http://www.dotnetperls.com/do
I'm writing a grade calculator, and at the end, I ask the user if they have another grade to calculate.
Console.Write("Do you have another grade to calculate? ");
moreGradesToCalculate = Console.ReadLine();
moreGradesToCalculate = moreGradesToCalculate.ToUpper();
I want to display a dialog box with the options of Yes or No.
I want to be able to run the program again, if the DialogResult is Yes, and do something else if the result is No.
You should use a do...while(...) loop.
I think it's not a good idea to run the whole program again, just start over getting numbers for calculating the grades (wrap your code in a loop).
For the DialogBox, simply import System.Window.Forms assembly and use this:
DialogResult result = MessageBox.Show("Do you want to start over?", "Question", MessageBoxButtons.YesNo);
if (result == DialogResult.No) {
// TODO: Exit the program
}
you can use do/while construct like
do {
Console.Write("Do you have another grade to calculate Y/N? ");
var moreGradesToCalculate = Console.ReadLine().ToUpper();
if(moreGradesToCalculate == "Y")
//do something
else if(moreGradesToCalculate == "N")
break;
}while(true);
If you want a dialog box, you'll have to add a reference to System.Windows.Forms and also add a using statement for the same namespace at the top of your file. Then you just have to check the result of calling the Show method on the MessageBox object at the end of a Do-While loop. For example:
do
{
// Grading calculation work...
}
while (MessageBox.Show("Do you have another grade to calculate?",
"Continue Grading?", MessageBoxButtons.YesNo) == DialogResult.Yes);
This will keep looping until the user clicks No.
If you don't want to keep using the mouse, do it all on the command line with this:
ConsoleKeyInfo key = new ConsoleKeyInfo();
do
{
// Grading work...
Console.WriteLine("\nDo you want to input more grades? (Y/N)");
do
{
key = Console.ReadKey();
}
while (key.Key != ConsoleKey.Y && key.Key != ConsoleKey.N);
}
while (key.Key == ConsoleKey.Y);
Here's a link to the reference material on looping - or 'Iteration Statements' from Microsoft. The Do-While is one of a few you should try to learn off by heart when you're just starting out:
http://msdn.microsoft.com/en-us/library/32dbftby.aspx