+ Post New Thread
Results 1 to 10 of 10
Coding Thread, C# .net - Adding two integers gives wrong result in Coding and Web Development; Ok, this is one of those errors I'm almost certain will have an obvious solution, but I've been banging my ...
  1. #1

    LosOjos's Avatar
    Join Date
    Dec 2009
    Location
    West Midlands
    Posts
    5,578
    Thank Post
    1,473
    Thanked 1,226 Times in 834 Posts
    Rep Power
    753

    C# .net - Adding two integers gives wrong result

    Ok, this is one of those errors I'm almost certain will have an obvious solution, but I've been banging my head for half hour now trying to figure out what's going on.

    In C#.net, I'm trying to keep a total record count, which is simply a container for the number of records counted in a function.

    I declare and initialise my total (iTotalRecords) as public so all functions can see it:

    Code:
    public partial class MainWindow : Form
        {
            public string AppPath="";
            public int iTotalRecords = 0;
            public int iExpectedRecords = 0;
    I then add records in the relevant place, at the same time adding to the total record:

    Code:
    if (StudentList.IndexOf(entry.Substring(8,4))>=0)
                    {
                        trOut.WriteLine(entry.Substring(0, 3) + centre + entry.Substring(8, entry.Length - 8));
                        iRecords += 1;
                        iTotalRecords += 1;
                    }
    All fine so far, and I know that iRecords is counting correctly as the output file has the result in it.

    However, when I later try to compare the two integers, iTotalRecords is coming out as exactly double what I would expect it to be, every time.

    I've checked that I haven't done anything daft like added to iTotalRecords twice (I haven't BTW).

    Can't think why it's doing this, it seems so simple!

    Any ideas?

  2. #2

    LosOjos's Avatar
    Join Date
    Dec 2009
    Location
    West Midlands
    Posts
    5,578
    Thank Post
    1,473
    Thanked 1,226 Times in 834 Posts
    Rep Power
    753
    And we're only talking a couple of hundred records, so it's not an overload...

  3. #3

    localzuk's Avatar
    Join Date
    Dec 2006
    Location
    Minehead
    Posts
    18,157
    Thank Post
    522
    Thanked 2,552 Times in 1,981 Posts
    Blog Entries
    24
    Rep Power
    877
    Can you post a more complete set of code?

  4. #4

    LosOjos's Avatar
    Join Date
    Dec 2009
    Location
    West Midlands
    Posts
    5,578
    Thank Post
    1,473
    Thanked 1,226 Times in 834 Posts
    Rep Power
    753
    Here's the complete source code for the relevant part of the program, I'd really appreciate any help, can't for the life of me figure out how the output is doubling!

    Code:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Collections;
    
    namespace ExamFileSplit
    {
        public partial class MainWindow : Form
        {
            public string AppPath="";
            public int iTotalRecords = 0;
            public int iExpectedRecords = 0;
    
            public MainWindow()
            {
                InitializeComponent();
            }
    
            private void btExamFile_Click(object sender, EventArgs e)
            {
                if (dlgExamFile.ShowDialog() == DialogResult.OK)
                {
                    txtExamFile.Text = dlgExamFile.FileName;
                }
            }
    
            private void btnOutputFolder_Click(object sender, EventArgs e)
            {
                if (dlgOutputFolder.ShowDialog() == DialogResult.OK)
                {
                    txtOutputFolder.Text = dlgOutputFolder.SelectedPath;
                }
            }
    
            private void btnOK_Click(object sender, EventArgs e)
            {
                //check that entry file and output folder have been selected
                if (txtExamFile.Text.Trim() == "" || txtOutputFolder.Text.Trim() == "")
                {
                    MessageBox.Show("You must specify the exam file you want to split and the folder to place split files in to",
                                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
    
                //find the exe path
                AppPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
                AppPath = AppPath.Substring(6, AppPath.Length - 6) + "\\";
    
                //initialize variables
                TextReader trConfig = null;
                int iCCount = 0;
    
    
                //check that config.ini exists
                try
                {
                    trConfig = new StreamReader(AppPath + "config.ini");
                }
                catch (System.IO.IOException err)
                {
                    MessageBox.Show(err.Message, "Configuration Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                
    
                //read config.ini
                ArrayList centres = new ArrayList();
                while (trConfig.Peek() >= 0)
                {
                    centres.Add(trConfig.ReadLine().Split(','));
                    iCCount += 1;
                }
    
                //check there is more than 1 centre listed
                if (iCCount <= 1)
                {
                    MessageBox.Show("One or less centre numbers were found in the configuration file", 
                                    "Configuration Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
    
                //validate config.ini
                foreach(string[] centre in centres)
                {
                    if(centre[0].Length!=5)
                    {
                        MessageBox.Show("Centre number " + centre[0] + " is invalid, it should be 5 digits in length",
                                        "Configuration Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
                        return;
                    }
    
                    if (centre.GetUpperBound(0) != 1)
                    {
                        MessageBox.Show("Your configuration file is not formatted correctly, please check." +
                                        "\n\nIt should contain a list of centre numbers and their post codes, " +
                                        "seperated by commas e.g.\n\t12345,AB1 2CD\n\t67891,EF3 4G",
                                        "Configuration Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
    
                //if config validated successfully, attempt to create the new exam files
                iTotalRecords = 0;
                string strError=null;
                foreach(string[] centre in centres)
                {
                    strError=createExamFile(centre[0], centre[1]);
                    if (createExamFile(centre[0], centre[1]) == null)
                    {
                        MessageBox.Show("Centre: " + centre[0] + "\nCompleted Successfully",
                                        "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("Centre: " + centre[0] + "\n" + strError,
                                        "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                
                //final check for possible missing entries
                if (iTotalRecords != iExpectedRecords)
                {
                    if (iTotalRecords > iExpectedRecords)
                    {
                        MessageBox.Show("A total of " + iTotalRecords.ToString() + " records were found, " +
                                        "but only " + iExpectedRecords.ToString() + " were expected.\n" +
                                        "Please check that you do not have duplicate candidate numbers in your configuration files.",
                                        "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else
                    {
                        MessageBox.Show("A total of " + iTotalRecords.ToString() + "records were found, " +
                                        "but only " + iExpectedRecords.ToString() + " were expected.\n" +
                                        "Please check that you have not omitted any candidate numbers from your configuration files.",
                                        "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
                else
                {
                    MessageBox.Show("Your exam file was split successfuly!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                
            }
    
            private string createExamFile(string centre, string PostCode)
            {
                //initialize variables
                TextReader trExamFile = null, trStudents=null;
                string strFileHeader = "", strCentreHeader = "", strCentreTrailer = "", strFileTrailer = "", strFileType = "";
                string strFile = this.txtExamFile.Text;
                int iRecords = 0;
    
                //attempt to open exam source file
                try
                {
                    trExamFile = new StreamReader(strFile);
                }
                catch (System.IO.IOException err)
                {
                    return err.Message;
                }
    
                //Validate the source fle as a valid exam entry or amendments file
                strFileHeader = trExamFile.ReadLine();
                if (strFileHeader.StartsWith("E1") || strFileHeader.StartsWith("A1"))
                {
                    strFileType = strFileHeader.Substring(0, 1);
                }
                else
                {
                    return "Specified file is not a valid exams entry or amendments file.";
                }
    
    
                //store exam ID and file sequence number
                string strExamBoard = strFile.Substring(strFile.Length-6, 2);
                string strExt = strFile.Substring(strFile.Length - 3, 3);
                
                //extract center header template
                strCentreHeader = trExamFile.ReadLine();
    
                //build student entry array
                ArrayList entries = new ArrayList();
                string strEntry;
    
                int x;
                for (x = 1; x > 0; x++)
                {
                    strEntry = trExamFile.ReadLine();
                    if (strEntry.StartsWith(strFileType + "5"))
                    {
                        entries.Add(strEntry);
                    }
                    else
                    {
                        strCentreTrailer = strEntry;
                        x = -1;
                    }
                }
    
                //read the final line - file trailer - and close file
                strFileTrailer = trExamFile.ReadLine();
                trExamFile.Close();
    
                //find the expected total number of records for validation later
                iExpectedRecords = Convert.ToInt32(strCentreTrailer.Substring(7, 7));
    
                //atempt to open the centres student list file
                try
                {
                    trStudents = new StreamReader(AppPath + centre + ".csv");
                }
                catch (System.IO.IOException err)
                {
                    return err.Message;
                }
    
                //load and count the student list
                iRecords = 0;
                ArrayList StudentList = new ArrayList();
                while (trStudents.Peek() >= 0)
                {
                    StudentList.Add(trStudents.ReadLine());
                    iRecords += 1;
                }
                trStudents.Close();
    
                if (iRecords == 0)
                {
                    return "No students listed in " + centre + ".csv";
                }
    
                StudentList.Sort();                
    
                //build centre entry file
                iRecords = 0;
                TextWriter trOut = new StreamWriter(this.txtOutputFolder.Text + "\\" + strFileType + centre + strExamBoard + "." + strExt.ToUpper());
    
                string strFHeader1 = strFileHeader.Substring(0, 2) + centre + strFileHeader.Substring(7, strFileHeader.Length - 7);
                trOut.WriteLine(strFHeader1);
    
                string strCHeader1 = strCentreHeader.Substring(0, 2) + centre + strCentreHeader.Substring(7, 9) + PostCode;
                trOut.WriteLine(strCHeader1.PadRight(strCentreHeader.Length, ' '));
    
                foreach (string entry in entries)
                {
                    if (StudentList.IndexOf(entry.Substring(8,4))>=0)
                    {
                        trOut.WriteLine(entry.Substring(0, 3) + centre + entry.Substring(8, entry.Length - 8));
                        iRecords += 1;
                        iTotalRecords += 1;
                    }
                }
    
                string strCTrailer1 = strCentreTrailer.Substring(0, 2) + centre + Convert.ToString(iRecords + 2).PadLeft(7, '0') + strCentreTrailer.Substring(14, strCentreTrailer.Length - 14);
                trOut.WriteLine(strCTrailer1);
    
                string strFTrailer1 = strFileTrailer.Substring(0, 2) + centre + Convert.ToString(iRecords + 4).PadLeft(7, '0') + strFileTrailer.Substring(14, strFileTrailer.Length - 14);
                trOut.WriteLine(strFTrailer1);
    
                trOut.Close();
    
                if (iRecords == 0)
                {
                    File.Delete(this.txtOutputFolder.Text + "\\" + strFileType + centre + strExamBoard + "." + strExt.ToUpper());
                    return "No students for this centre were found in the exam file";
                }
    
                return null;
            }
        }
    }

    If it's easier, I can upload the entire project to my DropBox

  5. #5

    Join Date
    Jan 2006
    Location
    Surburbia
    Posts
    2,178
    Thank Post
    74
    Thanked 307 Times in 243 Posts
    Rep Power
    115
    What about here?:

    Code:
                    strError=createExamFile(centre[0], centre[1]);
                    if (createExamFile(centre[0], centre[1]) == null)

    You're calling createExamFile() twice... probably need "if (strError == null)"

  6. Thanks to PiqueABoo from:

    LosOjos (22nd October 2010)

  7. #6

    Gatt's Avatar
    Join Date
    Jan 2006
    Posts
    6,772
    Thank Post
    873
    Thanked 674 Times in 443 Posts
    Rep Power
    503
    Am I missing it or have you not declared iRecords ?

  8. #7

    localzuk's Avatar
    Join Date
    Dec 2006
    Location
    Minehead
    Posts
    18,157
    Thank Post
    522
    Thanked 2,552 Times in 1,981 Posts
    Blog Entries
    24
    Rep Power
    877
    Quote Originally Posted by Gatt View Post
    Am I missing it or have you not declared iRecords ?
    top of the createExamFile method

  9. #8

    Gatt's Avatar
    Join Date
    Jan 2006
    Posts
    6,772
    Thank Post
    873
    Thanked 674 Times in 443 Posts
    Rep Power
    503
    Quote Originally Posted by localzuk View Post
    top of the createExamFile method
    Oh yeah there it is... :P

  10. #9

    Gatt's Avatar
    Join Date
    Jan 2006
    Posts
    6,772
    Thank Post
    873
    Thanked 674 Times in 443 Posts
    Rep Power
    503
    really need to get back into C#..

  11. #10

    LosOjos's Avatar
    Join Date
    Dec 2009
    Location
    West Midlands
    Posts
    5,578
    Thank Post
    1,473
    Thanked 1,226 Times in 834 Posts
    Rep Power
    753
    Quote Originally Posted by PiqueABoo View Post
    What about here?:

    Code:
                    strError=createExamFile(centre[0], centre[1]);
                    if (createExamFile(centre[0], centre[1]) == null)

    You're calling createExamFile() twice... probably need "if (strError == null)"
    I knew it'd be some daft mistake on my part! Thanks!

SHARE:
+ Post New Thread

Similar Threads

  1. Replies: 2
    Last Post: 12th June 2010, 06:37 AM
  2. Sims.net adding new personnel officer [solved]
    By sakwoya in forum MIS Systems
    Replies: 8
    Last Post: 10th March 2010, 12:05 PM
  3. Result! Training here i come!
    By jamin100 in forum Courses and Training
    Replies: 9
    Last Post: 1st February 2010, 11:58 AM
  4. Adding new staff in SIMS .NET
    By CESIL in forum MIS Systems
    Replies: 7
    Last Post: 18th March 2008, 03:23 PM
  5. Adding shortcuts to Sims.net
    By eejit in forum Windows
    Replies: 26
    Last Post: 22nd June 2005, 03:35 PM

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •