2

how to skip writing the value to the file if it = 0 in my calculator program

Procedure that writes the array into a file

 public void SaveArrayToFile()

        {
            int count;
            var writer = new System.IO.StreamWriter("C:/calc/calculations.txt",false);
            for (count = 0; count <= Results.Length -1 ; count++)
            {
                if (Results[count] == 0)
                {
                    // problem
                }
                writer.Write(Results[count]);
                writer.WriteLine();
            }
            writer.Dispose();

Any help would be valued

3
  • Use else, if your loop has a large body continues will make it unreadable Commented Apr 15, 2013 at 17:19
  • What do you want it to do if Results[count] == 0? Should it write an empty row to the file? Should it write a special value that means 'no data present'? Should it skip the row entirely? Skipping the row entirely is easy with the continue keyword, but if these results need to be read in by another program, that may not work. Commented Apr 15, 2013 at 17:20
  • 3
    Instead of saying writer.Dispose(); in the end, you should use a using statement: using (var writer = new StreamWriter("C:/calc/calculations.txt", false)) { for ... }. Commented Apr 15, 2013 at 17:32

5 Answers 5

12

Either

if (Results[count] == 0)
{
    continue;
}
writer.WriteLine(Results[count]);

or even simpler

if (Results[count] != 0)
{
    writer.WriteLine(Results[count]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks exactly what i needed i didn't know about continue
6

That's exactly what the continue statement is for.

if (Results[count] == 0)
{
    continue;
}

You could also solve this problem using Linq:

foreach (var result in Results.Where(r => r != 0))
{
    writer.Write(result);
    writer.WriteLine();
}

Comments

5
if (Results[count] != 0)
{
  writer.Write(Results[count]);
  writer.WriteLine();
}

Comments

4

Use the continue

//your code

if (Results[count] == 0)
{
    continue;
}

//your code

More (Jump Statement):

  • To terminate the loop use the break keyword.
  • To escape the current iteration use continue

Comments

3

simply:

if (Results[count] != 0)
{
       // Write it.
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.