Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Die tossing - writing to text file


The output part of the program is here:

using System;
using System.IO;

class C{

  public static void Main(){

    Die d = new Die();
    using(TextWriter tw = new StreamWriter(new FileStream("die.txt", FileMode.Create))){
      for(int i = 1; i <= 1000; i++){
        d.Toss();
        tw.WriteLine(d.NumberOfEyes());
      }
   }

  }

}

Take at look at the file written by your program. Here is an outline of the output written by my version of the program:

3
1
6
5
1
3
5
5
3
6
1
...

The reading part of the program is here:

using System;
using System.IO;

class C{

  public static void Main(){

    int[] count = new int[7];  // use 1..6.
    int numberOfEyes;

    for(int i = 1; i <= 6; i++) count[i] = 0;

    using(TextReader tr = new StreamReader(new FileStream("die.txt", FileMode.Open))){
      for(int i = 1; i <= 1000; i++){
        numberOfEyes = Int32.Parse(tr.ReadLine());
        count[numberOfEyes]++;
      }
   }

   for(int i = 1; i <= 6; i++)
     Console.WriteLine("Number of {0}: {1}", i, count[i]);

  }

}

Based on the input read by the program, it generates the following on standard output - the screen:

Number of 1: 170
Number of 2: 140
Number of 3: 189
Number of 4: 184
Number of 5: 160
Number of 6: 157