How to go to the next value of a While loop - c#

I have a While loop that reads a line of a file.txt. I also have a method named VerifyPhoto that returns true/false I want to go to next item of the while loop if the returned value is false. How Could I do that ? I tried break and return but it just leave all and back to the form...
while (!reader.EndOfStream)
{
if(VerifyPhoto(filed.matriculation) == false)
{
//go to the next line of the file.txt
}
}

You may want to get familiar with other control statement: continue
[EDIT] Newest version of the doc: continue, thanks Jeppe.

continue; (some more to make it 30 chars)

Depending on your actual code, maybe you could simply invert the boolean test, so you do something only if VerifyPhoto returns true:
while (...)
{
if(VerifyPhoto(filed.matriculation))
{
// Do the job
}
}

The continue statement passes control to the next iteration of the enclosing iteration statement in which it appears
while (!reader.EndOfStream)
{
if(VerifyPhoto(filed.matriculation) == false)
{
continue;
//go to the next line of the file.txt
}
}

Am I missing something in the way you are doing this?
Do you read the first line before starting the loop?
if so don't you need something like
**string line;**
while (!reader.EndOfStream)
{
if(VerifyPhoto(filed.matriculation) == false)
{
//go to the next line of the file.txt
**line = file.ReadLine();**
}
}

If you're trying to read line by line then File.ReadLines may be useful.
Also what you're looking for is the continue statement.
string myFile = #"c:\path\to\my\file.txt";
foreach(string line in File.ReadLines(myFile))
{
//Do stuff
//if(!VerifyPhoto())
// continue;
//Do other logic
}

Related

foreach(string token in text.Split(";")) scans only for one value

I am trying to get better in C# and so I thought making a simple programming language that can run basic commands like println("Hi"); and print("Hi");
However, the code shown scans for one foreach() value, my C# code:
string text = File.ReadAllText(inputFile);
string[] fileText = text.Split(";");
foreach (string token in fileText) {
if (token.StartsWith("println(") && token.EndsWith(")")) {
if (token.Split("\"").Length == 3) {
Console.WriteLine(token.Split("\"")[1]);
} else {
throw new Exception($"println(string); takes exactly 3 arguments of which {token.Split("\"").Length} were given.");
}
} else if (token.StartsWith("println(")) {
throw new Exception("Syntax error");
} else if (token.StartsWith("print(") && token.EndsWith(")")) {
if (token.Split("\"").Length == 3) {
Console.Write(token.Split("\"")[1]);
} else {
throw new Exception(($"print(string); takes exactly 3 arguments of which {token.Split("\"").Length} were given."));
}
} else if (token.StartsWith("print(")) {
throw new Exception("Syntax error");
}
}
My testing file:
print("This ");
println("is a test.");
I only get This as output.
You have stated in a comment (now in the question proper) that text is populated with:
string text = File.ReadAllText(inputFile);
That means a split based on semi-colons will give you the following strings (though the third depends on what comes after the final semi-colon):
print("This ")
<newline>println("is a test.")
<possibly-newline-but-irrelevant-for-this-question>
In other words, that second one does not start with println(, which is why your code is not picking it up. You may want to rethink how you're handling that, especially if you want to handle indented code as well.
I'd (at least initially) opt for stripping all white-space from the beginning and end of token before doing any comparisons.
What #paxdiablo said but the following will also work for the input shown:
var lines = File.ReadAllLines(inputFile); // ReadAllLines, not ReadAllText
foreach (string line in lines) {
var token = line.TrimEnd(new []{';'});
// your code here

How to use Console.ReadLine() in a while statement

Im looping a question untill the user puts in the value i want to accept. In this case its a number with a dash and it should be 7 'symbols' long.
My problem is putting the ReadLine inside of the while() statement.
So this is my code:
string cpr = "";
do
{
cpr = Console.ReadLine(); //I dont want ReadLine here :/
} while (
//I want Console.ReadLine() here
cpr.Length != 7
&&
!Regex.IsMatch(cpr, #"^[0-9-]+$")
&&
Regex.IsMatch(cpr, #"^[a-z]+$")
);
Putting ReadLine in a while statement is possible i have some other code that works while try parsing an int
do
{
//do something here
} while (!int.TryParse(Console.ReadLine(), out int1));
Try something like this:
string cpr = "";
bool condition = true;
while (condition )
{
cpr = Console.ReadLine();
if(cpr is ok)
{
condition = false;
}
}
While I agree with the comments (in that this isn't the best way to approach this - in fact, the code you've provided is more than adequate), you can do assignment inside of a conditional statement. ie.
var str = "";
do
{
...
} while ((str = Console.ReadLine()).Length != 7 && Regex.IsMatch(str, ...));
Except in this case, you'd need to use a while loop, instead of a do-while (since you won't capture input until the end of the loop with the do-while pattern).

How to repeat one loop in foreach

Hi guys how can you repeat one iteration in a foreach?
foreach (string line in File.ReadLines("file.txt"))
{
// now line == "account", next line == "account1"
if (line.Contains("a"))
//next loop take "account1";
else
// need to set that next loop will take line == "account" again
}
How to do it?
While I don't fully understand your example, I think I understand your question. I had the same problem and was able to come up with a solution: include a while loop within the foreach. In your example it would look like this:
foreach (string line in File.ReadLines("file.txt"))
{
bool repeat = true;
while (repeat)
{
// now line == "account", next line == "account1"
if (line.Contains("a"))
{
//do your logic for a break-out case
repeat = false;
}
else
{
//do your logic for a repeat case on the same foreach element
//in this instance you'll need to add an "a" to the line at some point, to avoid an infinite loop.
}
}
}
I know I'm very late to the game, but hopefully this will be helpful for anyone else who stumbles in here with the same problem.
There is no need to change your code, assuming it only has an if/else construct in the loop.
When the if condition evaluates to true the else will not execute and the loop resumes.
In a more complex where you want to immediately resume the loop and ensure nothing else following the condition executes, use the continue statement:
The continue statement passes control to the next iteration of the enclosing while, do, for, or foreach statement in which it appears.
foreach (string line in File.ReadLines("file.txt"))
{
// now line == "account", next line == "account1"
if (line.Contains("a"))
continue;
else
// need to set that next loop will take line == "account" again
// more stuff that we don't want to execute if line.Contains("a")
}
I guess this might also helpful if someone else come
for (int i = 0; i < inventoryTimeBlocks.Count; i++)
{
if (line.Contains("a"))
//next loop take "account1";
else
{
if(i > 0)
{
i = i - 1;
continue;
}
}
}

C# , what behavior does continue in a while produce?

I have a C# while loop, does a continue in this loop issue the same behaviour as moving to the next item in the loop? Exactly the same as for a "for loop".
For example see any problems in the following code sample?
while ((line = file.ReadLine()) != null)
{
string messageDownloadID = line ;
if (String.IsNullOrEmpty(messageDownloadID))
{
continue;
}
}
Thanks in advance.
I have a C# while loop, does a continue in this loop issue the same behaviour as moving to the next item in the loop? Exactly the same as for a "for loop".
No, a continue does not have the behavior of moving to the next item unless the part of the while block that moves to the next item is part of the loop condition or occurs and is executed before the continue statement. A continue will move you to the next iteration of the loop. The continue statement always starts a new iteration in the nearest enclosing while, do, for or foreach statement. But if in a while loop, say, i++ occurs after the continue statement it will not be executed. It is NOT exactly the same as a for loop.
The semantics of continue are like so:
while(condition) {
statement
continue
statement
}
is equivalent to
top:
while(condition) {
statement
goto top;
statement
}
In this case, the statements after the continue will never be executed if the continue is executed. But, for example, these two loops have different semantics:
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue;
}
Console.WriteLine(i);
}
int j = 0;
while (j < 10) {
if (j == 5) {
continue;
}
Console.WriteLine(j);
j++;
}
The former loop will print 0 through 9 on the console while the second will enter an infinite loop after print 0 through 4 on the console.
For example see any problems in the following code sample?
while ((line = file.ReadLine()) != null) {
string messageDownloadID = line;
if (String.IsNullOrEmpty(messageDownloadID)) {
continue;
}
}
Well, it depends. First, this loop isn't doing anything really except moving the file pointer in file to the end of the file. Now, assuming that you meant to have statements after the if statement like so
while ((line = file.ReadLine()) != null) {
string messageDownloadID = line;
if (String.IsNullOrEmpty(messageDownloadID)) {
continue;
}
ProcessMessageDownloadID(messageDownloadID);
}
then your code is fine. This is because the part of the while that moves to the next item is part of the while condition (see my bolded statement above) and thus will be executed every iteration of the loop. Your code is a standard pattern for parsing a file and skipping over items that can't be parsed (because they are, say, blank).
Yes, continue moves to the next iteration of the loop.
Yes, a continue call will restart the loop. Kind of like a goto to a label at the start of the loop.
Yes.
"A while loop can be terminated when a break, goto, return, or throw statement transfers control outside the loop. To pass control to the next iteration without exiting the loop, use the continue statement."

Continue in while inside foreach

In the following C# code snippet
I have a 'while' loop inside a 'foreach' loop and I wish to jump to the next item in 'foreach' when a certain condition occurs.
foreach (string objectName in this.ObjectNames)
{
// Line to jump to when this.MoveToNextObject is true.
this.ExecuteSomeCode();
while (this.boolValue)
{
// 'continue' would jump to here.
this.ExecuteSomeMoreCode();
if (this.MoveToNextObject())
{
// What should go here to jump to next object.
}
this.ExecuteEvenMoreCode();
this.boolValue = this.ResumeWhileLoop();
}
this.ExecuteSomeOtherCode();
}
'continue' would jump to the beginning of the 'while' loop not the 'foreach' loop.
Is there's a keyword to use here, or should I just use goto which I don't really like.
Use the break keyword. That will exit the while loop and continue execution outside it. Since you don't have anything after the while, it would loop around to the next item in the foreach loop.
Actually, looking at your example more closely, you actually want to be able to advance the for loop without exiting the while. You can't do this with a foreach loop, but you can break down a foreach loop to what it actually automates. In .NET, a foreach loop is actually rendered as a .GetEnumerator() call on the IEnumerable object (which your this.ObjectNames object is).
The foreach loop is basically this:
IEnumerator enumerator = this.ObjectNames.GetEnumerator();
while (enumerator.MoveNext())
{
string objectName = (string)enumerator.Value;
// your code inside the foreach loop would be here
}
Once you have this structure, you can call enumerator.MoveNext() within your while loop to advance to the next element. So your code would become:
IEnumerator enumerator = this.ObjectNames.GetEnumerator();
while (enumerator.MoveNext())
{
while (this.ResumeWhileLoop())
{
if (this.MoveToNextObject())
{
// advance the loop
if (!enumerator.MoveNext())
// if false, there are no more items, so exit
return;
}
// do your stuff
}
}
The following should do the trick
foreach (string objectName in this.ObjectNames)
{
// Line to jump to when this.MoveToNextObject is true.
this.ExecuteSomeCode();
while (this.boolValue)
{
if (this.MoveToNextObject())
{
// What should go here to jump to next object.
break;
}
}
if (! this.boolValue) continue; // continue foreach
this.ExecuteSomeOtherCode();
}
The break; keyword will exit a loop:
foreach (string objectName in this.ObjectNames)
{
// Line to jump to when this.MoveToNextObject is true.
while (this.boolValue)
{
// 'continue' would jump to here.
if (this.MoveToNextObject())
{
break;
}
this.boolValue = this.ResumeWhileLoop();
}
}
Use goto.
(I guess people will be mad with this response, but I definitely think it's more readable than all other options.)
You can use "break;" to exit the innermost while or foreach.

Categories

Resources