Hey guys can you tell me how should can I call "print: if . It never goes inside print if . It loops out.
static void Main(string[] args)
{
if (commands == "Read" || commands == "read")
{
fileread obj = new fileread();
lcsString = obj.getlcs();
commands = Console.ReadLine(); // If command = print I want it go to print but it never goes . it loops out
}
else if (commands =="print")
{
}
}
You can use while, here you go..
while (!commands.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
if (commands.Equals("read", StringComparison.OrdinalIgnoreCase))
{
fileread obj = new fileread();
lcsString = obj.getlcs();
}
else if (commands == "print")
{
// print ...
}
commands = Console.ReadLine();
}
It is not clear what you asking but looks like there is an option;
Moving your commands = Console.ReadLine() outside in your if statement. Like;
commands = Console.ReadLine();
if (commands == "Read" || commands == "read")
{
fileread obj = new fileread();
lcsString = obj.getlcs();
}
else if (commands =="print")
{
}
Because if your first if statement works, that's mean your command is Read or read. After that, your program doesn't go your else if part. It goes outside of your if statement.
Related
So im making a simple register and login in unity and ive came across a wall. My code works fine if it has any character or word in it but with it blank the loop doesnt work because it is a while line != null. I know that is the problem but i dont know any other loops to use in this scenario. Im using streamreader so i can constantly update the file as i can close it.
v
if (Input.GetKeyDown(KeyCode.Return))
{
StreamReader sr = new StreamReader("C:/Users/jorda/OneDrive/2D GAME REMAKE/Assets/login.txt",true);
line = sr.ReadLine();
while (line != null)
{
change =false;
if (line == Logdetails)
{
Debug.LogWarning("Account already exists");
username.GetComponent<InputField>().text = "";
password.GetComponent<InputField>().text = "";
break;
}
else if (Username == "" || Password == "")
{
Debug.LogWarning("There is an empty field");
break;
}
else
{
change = true;
}
line = sr.ReadLine();
}//while loop ends
sr.Close();
if (change == true)
{
Write();
}
}
public void Write()
{
StreamWriter sw = new StreamWriter("C:/Users/jorda/OneDrive/2D GAME REMAKE/Assets/login.txt", true);
{
sw.WriteLine(Logdetails);
username.GetComponent<InputField>().text = "";
password.GetComponent<InputField>().text = "";
sw.Close();
SceneManager.LoadScene(1);
}
}
Use a do while loop, which makes sure the code runs at least once, meaning for empty files one of your else branches is executed:
do
{
change =false;
if (line == Logdetails)
{
...
}
...
}
while(line != null)
I am trying to escape a while loop. Basically, if the "if" condition is met, I would like to be able to exit this loop:
private void CheckLog()
{
while (true)
{
Thread.Sleep(5000);
if (!System.IO.File.Exists("Command.bat"))
continue;
using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
if (s.Contains("mp4:production/CATCHUP/"))
{
RemoveEXELog();
Process p = new Process();
p.StartInfo.WorkingDirectory = "dump";
p.StartInfo.FileName = "test.exe";
p.StartInfo.Arguments = s;
p.Start();
<< Escape here - if the "if" condition is met, escape the loop here >>
}
}
}
}
}
Use break; to escape the first loop:
if (s.Contains("mp4:production/CATCHUP/"))
{
RemoveEXELog();
Process p = new Process();
p.StartInfo.WorkingDirectory = "dump";
p.StartInfo.FileName = "test.exe";
p.StartInfo.Arguments = s;
p.Start();
break;
}
If you want to also escape the second loop, you might need to use a flag and check in the out loop's guard:
boolean breakFlag = false;
while (!breakFlag)
{
Thread.Sleep(5000);
if (!System.IO.File.Exists("Command.bat")) continue;
using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
if (s.Contains("mp4:production/CATCHUP/"))
{
RemoveEXELog();
Process p = new Process();
p.StartInfo.WorkingDirectory = "dump";
p.StartInfo.FileName = "test.exe";
p.StartInfo.Arguments = s;
p.Start();
breakFlag = true;
break;
}
}
}
Or, if you want to just exit the function completely from within the nested loop, put in a return; instead of a break;.
But these aren't really considered best practices. You should find some way to add the necessary Boolean logic into your while guards.
break or goto
while ( true ) {
if ( conditional ) {
break;
}
if ( other conditional ) {
goto EndWhile;
}
}
EndWhile:
But you might also want to look into a very different approach, listening for file-system events.
If you need to continue with additional logic use...
break;
or if you have a value to return...
return my_value_to_be_returned;
However, looking at your code, I believe you will control the loop with the revised example below without using a break or return...
private void CheckLog()
{
bool continueLoop = true;
while (continueLoop)
{
Thread.Sleep(5000);
if (!System.IO.File.Exists("Command.bat")) continue;
using (System.IO.StreamReader sr = System.IO.File.OpenText("Command.bat"))
{
string s = "";
while (continueLoop && (s = sr.ReadLine()) != null)
{
if (s.Contains("mp4:production/CATCHUP/"))
{
RemoveEXELog();
Process p = new Process();
p.StartInfo.WorkingDirectory = "dump";
p.StartInfo.FileName = "test.exe";
p.StartInfo.Arguments = s;
p.Start();
continueLoop = false;
}
}
}
}
}
Which loop are you trying to exit? A simple break; will exit the inner loop. For the outer loop, you could use an outer loop-scoped variable (e.g. boolean exit = false;) which is set to true just before you break your inner loop. After the inner loop block check the value of exit and if true use break; again.
"break" is a command that breaks out of the "closest" loop.
While there are many good uses for break, you shouldn't use it if you don't have to -- it can be seen as just another way to use goto, which is considered bad.
For example, why not:
while (!(the condition you're using to break))
{
//Your code here.
}
If the reason you're using "break" is because you don't want to continue execution of that iteration of the loop, you may want to use the "continue" keyword, which immediately jumps to the next iteration of the loop, whether it be while or for.
while (!condition) {
//Some code
if (condition) continue;
//More code that will be skipped over if the condition was true
}
Sorry for the necro-add, but there's something I really wanted to insert that's missing in the existing answers (for anyone like me stumbling onto this question via google): refactor your code. Not only will it make it easier to read/maintain, but it'll often remove these types of control-routing issues entirely.
Here's what I'd lean towards if I had to program the function above:
private const string CatchupLineToIndicateLogDump = "mp4:production/CATCHUP/";
private const string BatchFileLocation = "Command.bat";
private void CheckLog()
{
while (true)
{
Thread.Sleep(5000);
if (System.IO.File.Exists(BatchFileLocation))
{
if (doesFileContainStr(BatchFileLocation, CatchupLineToIndicateLogDump))
{
RemoveLogAndDump();
return;
}
}
}
}
private bool doesFileContainStr(string FileLoc, string StrToCheckFor)
{
// ... code for checking the existing of a string within a file
// (and returning back whether the string was found.)
}
private void RemoveLogAndDump()
{
// ... your code to call RemoveEXELog and kick off test.exe
}
I'm writing a flesch index calculator and I want to be able to start my program with a console command and the .exe itself. I want to read in .txt files in the console with the command fleschIndexCalc.exe -f "path of the file" and then be able to select the calculation formula either for an english text with the parameter -e or a german text with -g.
When I start it with the console command: I type in the parameters by myself.
When I start it with the .exe: The program asks for the language and I just have to write g ore and press enter.
Now my question: how can I tell my program while starting it with the console that I already chose the language so it doesn't ask me for it again like I started it with the .exe?
Here's what I got:
(If you need more code from my FleschScore.cs ask for it :) )
namespace Flesch_Reading_Ease
{
public class Program
{
public static void Main(string[] args)
{
string fileName = string.Empty;
string[] parameters = new string[] { "-f", "-g", "-e" };
Console.WriteLine("Flesch Reading Ease");
Console.WriteLine("");
if (args.Length == 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("error!");
Console.ResetColor();
Console.WriteLine("no file found!");
Console.WriteLine("");
Console.Write("press any key...");
Console.ReadKey();
return;
}
foreach (string arg in args)
{
//------- WHAT TO WRITE HERE? -------
}
fileName = args[0];
FleschScore fs = new FleschScore(fileName);
fs.Run();
}
}
}
My method to choose the language looks like this:
private void SelectLanguage()
{
do
{
Console.WriteLine("choose language:");
Console.WriteLine("- german(g)");
Console.WriteLine("- english(e)");
string lang = Console.ReadLine();
switch (lang.ToUpper())
{
case "D":
_selectedLanguage = Language.German;
break;
case "E":
_selectedLanguage = Language.English;
break;
default:
_selectedLanguage = Language.Undefined;
Console.WriteLine("wrong input. Enter viable letter.");
Console.WriteLine("");
break;
}
} while (_selectedLanguage == Language.Undefined);
}
You basically loop through all the arguments and keep track of what's already entered. Then after that you check if you have all the info you need and pass everything as parameters to whatever method/class needs it.
bool isGerman = false;
bool isEnglish = false;
bool nextEntryIsFileName = false;
string filename = null;
foreach (string arg in args)
{
switch (arg)
{
case "-e":
isEnglish = true;
nextEntryIsFileName = false;
break;
case "-g":
isGerman = true;
nextEntryIsFileName = false;
break;
case "-f":
nextEntryIsFileName = true;
break;
default:
if (nextEntryIsFileName)
{
filename = arg;
nextEntryIsFileName = false;
}
break;
}
}
if (!(isEnglish ^ isGerman))
{
// Select language
}
if (String.IsNullOrEmpty(filename))
{
// Ask for filename
}
var language = ...
FleschScore fs = new FleschScore(language, fileName);
fs.Run();
Consider the following:
private void Read()
{
StreamReader r = new StreamReader(clientObject.GetStream());
string str = r.ReadLine();
if ((str == null) || (str == "")) { Disconnect(); }
Client_dataReceived(str);
Read();
}
When I connect this client to a server, it hangs. When I break it with Intellisense,
"string str = r.ReadLine();" is highlighted, I assume this is what the program was working on just before it started hanging. Why does it hang like this? I have created applications previously the exact same way, they don't hang.
Thanks in advance!
EDIT:
I just tried this:
private void Read()
{
StreamReader r = new StreamReader(clientObject.GetStream());
string str;
while ((str = r.ReadLine()) != null)
{
Client_dataReceived(str);
}
}
But I get the same effect...
private void Read()
{
StreamReader r = new StreamReader(clientObject.GetStream());
string str;
while (!(String.IsNullOrEmpty(str=r.ReadLine())))
{
Client_dataReceived(str);
}
}
Because it is a recursive call with no exit. You call Read inside of Read. It does not matter where it breaks.
private void Read()
{
StreamReader r = new StreamReader(clientObject.GetStream());
string str = r.ReadToEnd();
if ((str == null) || (str == "")) { Disconnect(); }
Client_dataReceived(str);
}
You have a recursive call. You will eventually get a StackOverflowException. (How coincidental. I just realized that!)
Try this:
private void Read()
{
using (var r = new StreamReader(clientObject.GetStream()))
{
string str;
while ((str = r.ReadLine()) != null)
{
Client_dataReceived(str);
}
Disconnect();
}
}
NOTE: I intentionally removed your str == "" test, as returning an empty string doesn't mean you've read to the end of the stream, while a null return does. If you have a special case where the empty line is important to be triggered on, be sure to restore that test.
Now if the clientObject is something that waits for input, like a TcpClient, then you need to evaluate it differently. It would help if we knew what clientObject was.
I can't comment because of low reputation so I'm writing it here...
Try adding a return(); statement after disconnect(); in your first code snippet.
Im working with the custom compiler from MSDN website. When I try to compile/run some test code (drag and drop to .exe), the console window opens then closes instead of staying open until I choose to close it. How do I keep it open?
Source: http://msdn.microsoft.com/en-us/magazine/cc136756.aspx#S8
Program.cs
if (args.Length != 1)
{
// Display title, reset cursor to normal, add space
Console.WriteLine("Alt ver 1.0 (Alpha)");
Console.WriteLine();
Console.ReadLine();
try
{
Scanner scanner = null;
using (TextReader input = File.OpenText(args[0]))
{
scanner = new Scanner(input);
}
Parser parser = new Parser(scanner.Tokens);
CodeGen codeGen = new CodeGen(parser.Result, Path.GetFileNameWithoutExtension(args[0]) + ".exe");
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
Console.ReadLine();
}
} //if
add a Console.ReadLine();
at the last inside the try block
try this
if (args.Length != 1)
{
// Display title, reset cursor to normal, add space
Console.WriteLine("Alt ver 1.0 (Alpha)");
Console.WriteLine();
Console.ReadLine();
try
{
Scanner scanner = null;
using (TextReader input = File.OpenText(args[0]))
{
scanner = new Scanner(input);
}
Parser parser = new Parser(scanner.Tokens);
CodeGen codeGen = new CodeGen(parser.Result, Path.GetFileNameWithoutExtension(args[0]) + ".exe");
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
Console.ReadLine();
}
finally
{
Console.Readkey();
}
} //if
else
{
Console.WriteLine("no args");
Console.ReadKey();
}
EDIT:--- passing argument problem
i have made this program and it works perfectly as far as getting filename as arguments
please have a look
class Program
{
static void Main(string[] args)
{
if (args.Length > 0)
{
foreach (var arg in args)
{
Console.WriteLine(arg);
}
Console.ReadKey();
}
else
{
Console.WriteLine("NO ARGS");
var fileName = Console.ReadLine();
Main(new string[] { fileName });
}
}
}