Repeat Forever a If Function - c#

I'm developing a simple project, but how I can do a repeat forever a If function(It's like a command-line)? Thanks.
My code is like this:
Console.Write("> ");
var Command = Console.ReadLine();
if (Command == "About") {
Console.WriteLine("This Operational System was build with Cosmos using C#");
Console.WriteLine("Emerald OS v0.01");
}

By any chance do you mean:
while( !(!(!(( (true != false) && (false != true) ) || ( (true == true) || (false == false) )))) == false )
{
Console.Write("> ");
if ("About" == Console.ReadLine())
{
Console.WriteLine("This Operational System was build with Cosmos using C#");
Console.WriteLine("Emerald OS v0.01");
}
}

string Command;
while (true) {
Command = Console.ReadLine();
if (Command == "About") {
Console.WriteLine("This Operational System was build with Cosmos using C#");
Console.WriteLine("Emerald OS v0.01");
}
}

Your question is unclear, but you probably want to do something like this:
while(true) { //Loop forever
string command = Console.ReadLine();
if (command.Equals("Exit", StringComparison.OrdinalIgnoreCase))
break; //Get out of the infinite loop
else if (command.Equals("About", StringComparison.OrdinalIgnoreCase)) {A
Console.WriteLine("This Operational System was build with Cosmos using C#");
Console.WriteLine("Emerald OS v0.01");
}
//...
}

I don't think your question is really clear. But here is an attempt :)
while (true) {
if (i ==j ) {
// whatever
}
}

You mean this?
while(true) {
if( ...) {
}
}
PS: this is one of my favourite preprocessor hacks. Doesn't work in C# though, only C/C++.
#define ever (;;)
for ever {
//do stuff
}

I think you just want a simple while loop with (at least) one exit point.
while(true)
{
Console.Write("> ");
var command = Console.ReadLine();
if (command == "about") {
Console.WriteLine("This Operational System was build with Cosmos using C#");
Console.WriteLine("Emerald OS v0.01");
} else if (command == "exit") {
break; // Exit loop
}
}

You can't use an 'if' statement by itself because when it gets to the end your program will continue executing the next statement in your code. I think what you're after is a 'while' statement that always evaluates to true.
e.g.
string Command;
while(true)
{
Command = Console.ReadLine();
if (Command == "About")
{
Console.WriteLine("This Operational System was build with Cosmos using C#");
Console.WriteLine("Emerald OS v0.01");
}
}
This loop will be inescapable unless an exception is thrown or you execute a break statement (or whatever the equivalent is in C#, I'm a Java guy - don't hate me).

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

Console program with multiple parameters

I am currently writing a console program using .NET Core for Windows and want to execute certain functions with parameters, for example program.exe /a /b. Unfortunately this does not work as I thought and therefore only the first specified parameter is executed, but not several in a row.
I have already tried the following and have tried to change it minimally several times:
static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine("Please give me one or more parameters to continue.");
return;
}
var command = args[0];
switch (command)
{
case "/?":
Console.WriteLine("Some help text ..");
break;
case "/a":
Console.WriteLine("a");
break;
case "/b":
Console.WriteLine("b");
break;
}
}
Any idea(s) for me?

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# 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

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;

Categories