Jump to content

Help with simple program

- - - - -

  • Please log in to reply
1 reply to this topic

#1
vernacular26

vernacular26

    Newbie

  • Members
  • Pip
  • 2 posts
Window form application.
Trying to read a .txt file which is a list of integers and insert them into an array.
Says there is an unhandled exception in the while loop.


{
    public partial class Form1 : Form
    {
        private StreamReader inFile;
 
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            int[] grades = new int[40];
            int countGrades = 0;
            int totalScores = 0;
            int arrayIndex = 0;
            double avgGrade = 0;
            string inValue;


            if (File.Exists("Grades.txt"))
            {
                inFile = new StreamReader("Grades.txt");
            } 
            else
            {
                lblMsg.Text = "File not found";
            }

            for (int i = 0; i-1 < countGrades; i++)
            {
                while ((inValue = inFile.ReadLine()) != null)
                {
                        grades[arrayIndex++] = Convert.ToInt32(inValue);
                }
                
                grades[i] = Convert.ToInt32(inValue);
                
                totalScores += grades[i];

                countGrades++;
            }
        
            lblMsg.Text = Convert.ToString(grades[0]);
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            inFile.Close();
        }

   
    }

Edited by Alexander, 04 November 2010 - 06:19 PM.
Added [code] tags.


#2
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
The code can't be sure that the lines in the file are actually integers, so the convert might fail if it isn't.
Try

int value;

if( Integer.TryParse(inValue, value) ){

  //Success

} else {

  //Fail

}





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users