I am trying to make a program that looks for prime numbers, displays them in the console and stores the numbers in a file. The program already stores the numbers in a file, but it doesn't display the numberrs in the console. Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Priemgetallen
{
class Program
{
static void Main()
{
using (StreamWriter writer = new StreamWriter("C://Users//mens//Documents//PriemGetallen.txt"))
{
Console.SetOut(writer);
Act();
}
}
static void Act()
{
double maxGetal = double.MaxValue;
Console.WriteLine("--- Primes between 0 and 100 ---");
for (int i = 0; i < maxGetal; i++)
{
bool prime = PrimeTool.IsPrime(i);
if (prime)
{
Console.Write("Prime: ");
Console.WriteLine(i);
}
}
}
public static class PrimeTool
{
public static bool IsPrime(int candidate)
{
// Test whether the parameter is a prime number.
if ((candidate & 1) == 0)
{
if (candidate == 2)
{
return true;
}
else
{
return false;
}
}
// Note:
// ... This version was changed to test the square.
// ... Original version tested against the square root.
// ... Also we exclude 1 at the end.
for (int i = 3; (i * i) <= candidate; i += 2)
{
if ((candidate % i) == 0)
{
return false;
}
}
return candidate != 1;
}
}
}
}
That's because of the line
Console.SetOut(writer);
. You are sending console output to the file.Rather than do it the way you are, ditch the
StreamWriter
and instead use: