Unbreakable loop - c#

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 == "".

Related

How to get a console to read through all conditions

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.

C# console application executing code when Console.ReadLine() executes

I'm currently messing around with a Console application and I have some logic to get user input for 3 different things. I have the application designed so that the user can type 'Q' or 'q' at any time to exit the program. However, the way I am currently accomplishing this is through if statements after each user input (using the Console.ReadLine().)
A solution I thought of that would be better is to have a piece of code in one place that exits the program and is called automatically when the ReadLine() is executed and checks the input to see if it is 'q' or 'Q'. I was curious if there was any way to do something like this???
Here is the code I have now
Console.WriteLine("Please give me a source and destination directory...(Enter 'Q' anytime to exit)");
Console.Write("Enter source path: ");
_sourcePath = Console.ReadLine();
if (_sourcePath.Equals("q", StringComparison.CurrentCultureIgnoreCase))
{
Environment.Exit(Environment.ExitCode);
}
Console.Write("Enter destination path: ");
_destinationPath = Console.ReadLine();
if (_destinationPath.Equals("q", StringComparison.CurrentCultureIgnoreCase))
{
Environment.Exit(Environment.ExitCode);
}
Console.Write("Do you want detailed information displayed during the copy process? ");
string response = Console.ReadLine();
if (response.Equals("q", StringComparison.CurrentCultureIgnoreCase))
{
Environment.Exit(Environment.ExitCode);
}
if (response?.Substring(0, 1).ToUpper() == "Y")
{
_detailedReport = true;
}
It would be nice to remove the if blocks and just have the incoming value from the Console.ReadLine() checked when it is executed...
You can create a function to get the user's input and after the Console.ReadLine() just do any processing (exiting on 'q') on the input before returning it.
static void Main(string[] args)
{
Console.Write("Enter source path: ");
var _sourcePath = GetInput();
Console.Write("Enter destination path: ");
var _destinationPath = GetInput();
Console.Write("Do you want detailed information displayed during the copy process? ");
var response = GetInput();
var _detailedReport = response?.Substring(0, 1)
.Equals("y", StringComparison.CurrentCultureIgnoreCase);
}
private static string GetInput()
{
var input = Console.ReadLine();
if (input.Equals("q", StringComparison.CurrentCultureIgnoreCase))
Environment.Exit(Environment.ExitCode);
return input;
}
I'm afraid there's no direct way to hook into the ReadLine() call. Wrapping it all in your own method called 'ReadLine' could work though, say something like
static string ReadLine()
{
string line = Console.ReadLine();
if (line.Equals("q", StringComparison.CurrentCultureIgnoreCase))
{
Environment.Exit(Environment.ExitCode);
}
//Other global stuff
return line;
}
//Elsewhere
Console.Write("Enter source path: ");
_sourcePath = ReadLine(); //Note: No 'Console.' beforehand. This is your method!
Console.Write("Enter destination path: ");
_destinationPath = ReadLine();
Console.Write("Do you want detailed information displayed during the copy process? ");
string response = ReadLine();
if (response?.Substring(0, 1).ToUpper() == "Y")
{
_detailedReport = true;
}

C# restart a while loop in the middle

I have a while loop that i want to restart if a condition is false, in my case. It is because i'm checking if a ip is valid and if it is then run the whole loop normal and if not i need it to restart from the start again at that point. I can't use a break and i dont want to use a goto. What is your sugestions?
This is my code, where i want to restart my while loop.
while (calculateAgain == "y")
{
Console.Write("Your ip here: ");
string ip = Console.ReadLine();
IpValidation(ip);
if (IpValidation(ip) == false)
{
Console.WriteLine("Ugyldig IP og eller Subnet mask!\n");
// goto or break
}
After this my code runs on a lot...
Tell me some solutions to this other than goto.
You need to use the word continue
if (IpValidation(ip) == false)
{
Console.WriteLine("Ugyldig IP og eller Subnet mask!\n");
continue;
}
This will skip the rest and go to the top of your loop.
There is the continue statement. If it will be hit it will skip back to the start of the loop.
while (calculateAgain == "y")
{
// ...
if (IpValidation(ip) == false)
{
Console.WriteLine("Ugyldig IP og eller Subnet mask!\n");
continue;
}
Console.WriteLine("This will not be executed when continue is called");
}
You can do this on two ways, (by using break or continue) break will exit the loop completely, continue will just skip the current iteration.
So by reading your question. You need to use continue here, so your example might look like this:
while (calculateAgain == "y")
{
Console.Write("Your ip here: ");
string ip = Console.ReadLine();
IpValidation(ip);
if (IpValidation(ip) == false)
{
Console.WriteLine("Ugyldig IP og eller Subnet mask!\n");
continue;
}
}
This above means, for condition if (IpValidation(ip) == false) code below will be skiped (will never be executed) if condition is satisfied

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

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