How to get a console to read through all conditions - c#

I have a console application that asks the user to choose one of three options and to be able to open an inventory if desired. However, instead of checking to see if any of the other conditions are true are false, the console just reads the conditions linearly and waits till the first one has been satisfied. So for example, in the code below, it runs the first bit of text, presents the options, and then waits for the user to enter "inventory" without considering the other options. What's up? Why does this happen? and how do I get the console to run through and check whether or not all conditions have been satisfied?
Here's the code
using System;
using System.IO;
namespace Feed_de_monky
{
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Green;
string one = "";
string two = "";
string inventory = "inventory";
int storyint = 0;
TextReader input = Console.In;
TextWriter output = Console.Out;
int options = 0;
if (storyint == 0)
{
Console.WriteLine("You are in a dark Jungle. You look into the darkness of the trees and see the silhouette of a tiger standing in front of you down the way.");
Console.WriteLine("");
Console.WriteLine("turn and run");
Console.WriteLine("pounce on tiger");
Console.WriteLine("climb a tree.");
options++;
if (input.ReadLine() == inventory)
{
output.WriteLine(one);
output.WriteLine(two);
return;
}
else if(input.ReadLine() == "turn and run" && options == 1)
{
output.WriteLine("");
output.WriteLine("The tiger chases you through the darkness. You never had a chance.");
Console.Write("Press any key to continue...");
Console.ReadKey(true);
}
else if(input.ReadLine() == "pounce on tiger" && options == 1)
{
output.WriteLine("");
output.WriteLine("The tiger is caught by surprise. You overwhelm the beast and he dies of shock and surprise on the spot");
one = "tiger skin";
output.WriteLine("TIGER SKIN ADDED TO YOUR INVENTORY");
storyint++;
options++;
}
else if(input.ReadLine() == "climb a tree" && options == 1)
{
output.WriteLine("");
output.WriteLine("You climb the tree. But while you sit on the branches believing yourself to be safe, the tiger jumps through the air and bites your head clean off. You never had a chance.");
Console.Write("Press any key to continue...");
Console.ReadKey(true);
}
Console.Write("Press any key to continue...");
Console.ReadKey(true);
}
}
}
}

I think you might need to set
var inputLine = input.ReadLine();
And then do your logic on the variable inputLine.
As you have it now I believe it will call ReadLine more times than you are expecting. But if you just call .ReadLine() one time and assign it to a variable that should act better than calling it repeatedly.

Related

Unbreakable loop

I am trying to break a loop by only inputing a white space but everytime I do this it keeps looping idk why is that. Is it probably by a logic problem or what is it because id what is going on/
Console.WriteLine("Please create a file with .doc .txt .pxt etc");
string fileName = Console.ReadLine();
writer1 = new StreamWriter($"{fileName}");
while (true)
{
while (choiceParsered == false && choiceRange == false)
{
Console.WriteLine("1) write a file");
Console.WriteLine(" 2. Copy a file ");
Console.WriteLine(" 3. Exit ");
choose = Console.ReadLine();
choiceParsered = int.TryParse(choose, out num);
}
if (choose == "1")
{
string writing = "m";
while (true)
{
Console.WriteLine("What do you want to drive on the file? write a blank space to finish");
writing = Console.ReadLine();
writer1.WriteLine(writing);
if (writing == " " || writing == "" )
{
break;
}
}
}
The problem is caused by this line
choiceParsered = int.TryParse(choose, out num);
Here you get true if the user types a valid input. Then, when you type "1" the variable choose is assigned and the code enters the second loop.
If you type a space or press enter the second loop exits without problems.
But then you never reenter the first loop because the variable choiceParsered is true and, thus, the code goes to test again choose and this is still "1" so the code enters again the second loop and never ends
To fix you need to move the test for the choices inside the first loop AND set the choiceParsered again to false before exiting the input loop.
while (choiceParsered == false && choiceRange == false)
{
Console.WriteLine(" 1. write a file");
Console.WriteLine(" 2. Copy a file ");
Console.WriteLine(" 3. Exit ");
choose = Console.ReadLine();
choiceParsered = int.TryParse(choose, out num);
if(choiceParsered)
{
if (choose == "1")
{
string writing = "m";
while (true)
{
Console.WriteLine("What do you want to drive on the file? write a blank space to finish");
writing = Console.ReadLine();
writer1.WriteLine(writing);
if (writing == " " || writing == "")
{
choiceParsered = false;
break;
}
}
}
}
But there is still the problem of the outer infinite loop. This will never ends if you cannot put a break to terminate it or set a condition to end if
Console.WriteLine("Please create a file with .doc .txt .pxt etc");
string fileName = Console.ReadLine();
writer1 = new StreamWriter($"{fileName}");
bool exitProgram = false;
while (!exitProgram)
{
....
if (choose == "3")
exitProgram = true;
}
Also you never close the StreamWriter. This is a very serious bug that leaves the file open and without a proper flush to end the writing.
But you can have the using statement to close the file for you, so replace the line that opens the file with
using writer1 = new StreamWriter($"{fileName}");
I assume you mean that it doesn't break out of the first while(true) loop. In that case it is because the break instruction you have only breaks out of the second while(true) loop. You'll need to either use a goto statement or some other logic. I think also you would want to do writing == null instead of writing == "".

How do I stop my C# console program from stopping when executing "console.readline();" twice

i'm really new to C# and i've been working on this really simple command line style program (that has custom commands and such). Now the commands work great but every time I allow the user to go back to enter another command or just anything it closes the program when I press enter. But only the second time I execute a command. I think this has something to do with console.WriteLine();
Here's my code (I've searched everywhere on how to fix this and nothing that i've found has worked)
using System;
namespace ConsoleProgram
{
class Program
{
private static string userEnteredCommand;
static void Main(string[] args)
{
Console.Title = "IAO Systems Service Console";
onCommandLineStart();
void onCommandLineStart()
{
Console.WriteLine("Copyright (C) 2018 IAO Corporation");
Console.WriteLine("IAO Systems Service Console (type 'sinfo' for more information.");
userEnteredCommand = Console.ReadLine();
}
void onCommandLineReturn()
{
userEnteredCommand = Console.ReadLine();
}
// Commands
if (userEnteredCommand == "sinfo")
{
Console.WriteLine(" ");
Console.WriteLine("Program information:");
Console.WriteLine("Created for IAO Corporation, by Zreddx");
Console.WriteLine("This program controls doors, gates and e.t.c within IAO Terratory.");
Console.WriteLine(" ");
Console.WriteLine("This program is protected by copyright, do not redistribute. ");
}
else
{
Console.WriteLine("That command does not exist, do 'programs' for a list of actions.");
}
onCommandLineReturn();
}
}
}
Console applications close when they get to the end of Main. It's exiting after the Console.ReadLine in onCommandLineReturn();.
Add a bool variable called keepLooping, set it to true, and wrap your code in a while(keepLooping) statement. Somewhere in your program flow, check for input like "quit" or "exit" and set the keepLooping variable to false.
Here's an example of it in a dotnetfiddle: https://dotnetfiddle.net/Jguj5k

How do I use if else statements in c#?

I'm from a python background and I'm finding it difficult to pick up the syntax in c#.
I'm trying to write code so that the program will continuously ask the user for input and it will echo it on the screen, but if the user input is 'exit' then it exits.
I tried
Console.WriteLine("Hello World!");
Console.Write("Enter some text: ");
string userinput = Console.ReadLine();
if (userinput == "exit")
{
Console.ReadKey();
}
else
{
Console.WriteLine(userinput);
But it doesn't achieve expected results
An if statement only executes once.
Since you're looking to take some action repeatedly, a do/while construct is more along the lines of what you need.
Something like this should at least get you started in the right direction:
string userinput;
do
{
Console.Write("Enter some text: ");
userinput = Console.ReadLine();
Console.WriteLine(userinput);
}
while (userinput != "exit");

Use of unassigned variable error in VS 2015

I'm having an issue with the answer2 string variable (about half way down, I included the entire main method because I wasn't sure if it would help or not). the compiler is telling me the variable is unassigned and ignoring the previous if-else block. I'm not quite sure how to fix it.
The first if statement after //scene 3 is where it starts (if (answer2 == "CONTACT");)
static void Main(string[] args) {
Console.Clear(); //just to clear up console
Random theftCalc = new Random(); //calclating theft skill
//int pcBuildSkill = 1;
int theftSkills = theftCalc.Next(1, 10); //read above
double dosh = 1000.0; //DOSH
bool hasParts = false;
//beginning of the story
Console.Write("You start your quest to build a PC\nbut you only have so much dosh ($" + dosh + ") ! What do you do?\n");
Console.WriteLine("Will you WORK for more dosh or will you STEAL parts\nfrom your local Best Buy?");
Console.WriteLine("You need to have a theft skill of more than 5 to properly steal from best buy\nand not get caught (current theft skill: " + theftSkills + ").");
//all this is to just calculate how much you made from working
Random rnd = new Random();
int randomNumber = rnd.Next(100, 400);
dosh = dosh + randomNumber;
String answer;
do {
answer = Console.ReadLine();
answer = answer.ToUpper();
if (answer == "WORK") {
Console.WriteLine("You put in hard work and dedication and earn $" + randomNumber + ", bringing your total dosh to $" + dosh + ". Now you can buy your parts!");
break;
} else if (answer == "STEAL") //the "STEAL" story
{
if (theftSkills > 5) {
Console.WriteLine("You successfully steal from Best Buy. You're a terrible person.");
hasParts = true;
break;
} else {
Console.WriteLine("You're caught stealing from Best Buy. Luckily, you get a slap on the wrists and you're sent home.");
}
break;
} else {
Console.WriteLine("That answer is invalid! Would you like to WORK or STEAL?");
}
} while (answer != "WORK" || answer != "STEAL");
//scene 2
Console.Clear();
Console.WriteLine("SCENE 2");
//second answer
//have to type something to coninue?
String answer2;
Console.WriteLine("Now you officially have your parts and can begin building! Press enter to continue");
if (answer == "WORK") {
Console.WriteLine("As you begin building, you run into a few issues. You don't know how to properly hook up the PSU!\nAs you were honorable and worked for your money, you can contact Geek Squad at Best Buy without being arrested! Would you like to CONTACT Geek Squad, CONTINUE building and see if you can get past the issue, or RESEARCH online the issue you're having?");
answer2 = Console.ReadLine();
answer2 = answer2.ToUpper();
do {
if (answer2 == "CONTACT") {
Console.WriteLine("You call up Geek Squad, but you're forced to wait on the phone for a representitive!\nEventually you get through, and they're due at your house in one hour.");
break;
} else if (answer2 == "CONTINUE") {
Console.WriteLine("You continue on your own, hoping nothing goes wrong to ruin your project.");
break;
} else if (answer2 == "RESEARCH") {
Console.WriteLine("Spending hours on the internet, you educate yourself properly on the inner workings of a computer and continue to build it proficiently.");
break;
} else {
Console.WriteLine("That answer is invalid, would you like to CONTACT, CONINUTE, or RESEARCH?");
}
} while (answer2 != "CONTACT" || answer2 != "CONTINUE" || answer2 != "RESEARCH");
} else if (answer == "STEAL") {
Console.WriteLine("As you begin building, you run into a few issues. You don't know how to properly hook up the PSU!\nAs you stole your parts, you can't contact Geek Squad at Best Buy without being arrested! Would you like to SELL your parts, CONTINUE building and see if you can get past the issue, or RESEARCH online the issue you're having?");
answer2 = Console.ReadLine();
answer2 = answer2.ToUpper();
do {
if (answer2 == "SELL") {
Console.WriteLine("You list your parts on craigslist as a lot, and wait for offers to come in");
break;
} else if (answer2 == "CONTINUE") {
Console.WriteLine("You continue on your own, hoping nothing goes wrong to ruin your project.");
break;
} else if (answer2 == "RESEARCH") {
Console.WriteLine("Spending hours on the internet, you educate yourself properly on the inner workings of a computer and continue to build it proficiently.");
break;
} else {
Console.WriteLine("That answer is invalid, would you like to CONTACT, CONINUTE, or RESEARCH?");
}
} while (answer2 != "SELL" || answer2 != "CONTINUE" || answer2 != "RESEARCH");
}
//scene 3 endings
Console.Clear();
Console.WriteLine("SCENE 3");
//picks between two endings for each
Random end = new Random();
int ending = end.Next(0, 10);
if (answer2 == "CONTACT") {
if (ending > 5) {
Console.WriteLine("Geek Squad arrives, and assembles your PC for you. Congratdulations! You've won! THE END");
} else {
Console.WriteLine("Geek Squad never arrives...you start to worry. Upon calling their center, it turns out their car was summoned to R'lyeh and consumed by Cthulhu. THE END");
}
} else if (answer2 == "SELL") {
if (ending > 5) {
Console.WriteLine("You craigslist ad is answered! You're still a horrible person for stealing. You meet the buyed, and what do you know it's the police. You're arrested for Grand Larceny and sentenced to four years in prison. THE END");
} else {
Console.WriteLine("A response for your ad comes in! You go to meet the buyer, and he stabs you to re-steal your stolen goods. Thiefs never win, you horrible person. THE END");
}
} else if (answer2 == "CONTINUE") {
if (ending > 7) {
Console.WriteLine("Your attempts at winging it have paid off! Everything is assembled, running fine! Congratdulations! THE END");
} else {
Console.WriteLine("After hours and hours of winging it, your PC lies on the ground in a mess of aluminum and silicon. Maybe you should've gotten professional help. THE END");
}
} else if (answer2 == "RESEARCH") {
Console.WriteLine("After spending a few hours on PC forums, you gain a wealth of knowledge about building machines. You adeptly assemble yours in no time, and have it running. THE END");
}
}
You declare a answer2 in section 2
And assign value to answer2 reading from console when
answer == "WORK"
or
answer == "STEAL"
But what if answer is not euqal to work or steal then answer2 will remain unassigned.
Try like this
String answer2=string.Empty;

Console.ReadLine() skips the first input character

Console.WriteLine("You have not installed Microsoft SQL Server 2008 R2, do you want to install it now? (Y/N): ");
//var answerKey = Console.ReadKey();
//var answer = answerKey.Key;
var answer = Console.ReadLine();
Console.WriteLine("After key pressed.");
Console.WriteLine("Before checking the pressed key.");
//if(answer == ConsoleKey.N || answer != ConsoleKey.Y)
if (string.IsNullOrEmpty(answer) || string.IsNullOrEmpty(answer.Trim()) || string.Compare(answer.Trim(), "N", true) == 0)
{
Console.WriteLine("The installation can not proceed.");
Console.Read();
return;
}
I have tried to input these:
y -> it gives me an empty string,
y(whitespace+y) -> it gives me the "y"
I have checked other similar posts, but none of them solves my problem.
The ReadLine() still skips the 1st input character.
UPDATE Solved, see below.
Suggested change:
Console.Write("Enter some text: ");
String response = Console.ReadLine();
Console.WriteLine("You entered: " + response + ".");
Key points:
1) A string is probably the easiest type of console input to handle
2) Console input is line oriented - you must type "Enter" before the input becomes available to the program.
Thank you all for replying my post.
It's my bad that not taking consideration of the multi-thread feature in my code. I will try to explain where I was wrong in order to say thank you to all your replies.
BackgroundWorker worker = .....;
public static void Main(string[] args)
{
InitWorker();
Console.Read();
}
public static void InitWorker()
{
....
worker.RunWorkerAsync();
}
static void worker_DoWork(....)
{
.....this is where I wrote the code...
}
The problem was I started a sub-thread which runs asynchronously with the host thread. When the sub-thread ran to this line : var answer = Console.ReadLine();
the host thread ran to the Console.Read(); at the same time.
So what happened was it looked like I was inputting a character for var answer = Console.ReadLine();, but it actually fed to the Console.Read() which was running on the host thread and then it's the turn for the sub-thread to ReadLine(). When the sub-thread got the input from keyboard, the 1st inputted character had already been taken by the host thread and then the whole program finished and closed.
I hope my explanation is clear.
Basically you need to change Console.Read --> Console.ReadLine

Categories