C# Xamarin Wrong If clause being used? - c#

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

Related

Ending a loop to return to next sequence

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.

C#, Getting user value and resetting it

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

How can I stop C# console application closing after correct pin entered and after three attemps?

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().

Why does the console close after I type yes?

I was making a calculator in C#. Here is the multiplication part---
using System;
static class calculator
{
public static void Main()
{
welcome:
Console.WriteLine("Welcome to my calculator, please press enter to continue");
Console.ReadLine();
Console.WriteLine("Do you want to add, subtract, multiply or divide?");
string x = Convert.ToString(Console.ReadLine());
if (x == "multiply")
{
Console.WriteLine("Please enter the first value");
decimal value1multiply = Convert.ToDecimal( Console.ReadLine());
Console.WriteLine("Please enter the second value" );
decimal value2multiply = Convert.ToDecimal(Console.ReadLine());
Console.WriteLine("Result =");
Console.WriteLine(value1multiply * value2multiply);
Console.WriteLine("Thank you for using my calculator!Do you still want to use it?Please answer in 'yes' or 'no' and press 'enter'");
Console.ReadLine();
string yesorno =Console.ReadLine();
if (yesorno == "yes")
{
goto welcome;
}
if (yesorno == "no")
{
Environment.Exit(0);
}
}
}
}
When I type 'yes' when it asks me to, the console should lead me to welcome. But instead, it does not lead me anywhere and remains blank. When I press enter again, the console closes. Why is this happening and how can I prevent it?
What I have tried:
I tried removing the environment.exit(0), thinking that the console was leading me to that but it did not help. I even tried typing the code in Visual Studio, but no difference in the outcome. (I use sharp develop)
Besides the use of goto, which is often frowned upon, you are using one too much ReadLine call.
Here:
Console.ReadLine();
string yesorno = Console.ReadLine();
Maybe you typed yes and then hit Enter twice. In that case yesorno would be empty and your check would fail. The first entry is swallowed by the first ReadLine that didn't got assigned to a variable.

how to re-display user prompt after invalid input is given in c#?

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

Categories