CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Mar 2012
    Posts
    0

    Help beginner with a simple code.

    Hey there guys I have been practicing C# from a book I purchased and I tried to write up a code today but I am not having much success with it so far so I was hoping you guys could maybe give me some insight on what I need to improve.

    As a short description the program is supposed to calculate the total revenue for tickets sold for a baseball game. Class a tickets are sold for $15, class b 12$ and class C for 9$. The application is supposed to allow the user to enter the number of each class ticket sold and then its supposed to display the income generated for each class of tickets and then a total revenue generated overall.

    I have already made up the UI which contains a bunch of description labels and also text boxes for the user to input the amount of tickets and also labels to display the totals. The code I have so far is:
    Code:
    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void calculateRevenueButton_Click(object sender, EventArgs e)
            {
                int classA = 15;  // Creating 4 ints to hold ticket prices
                int classB = 12;
                int classC = 9;
    
                int classAInput;  // Creating 3 ints to hold tickets sold input
                int classBInput;
                int classCInput;
    
                double totalClassA;   // Creating 4 doubles to hold total revenue values
                double totalClassB;
                double totalClassC;
                double totalRevenue;
    
                classAInput = int.Parse(classaTextBox.Text); //Assign int values to classinputs from user input
                classBInput = int.Parse(classbTextBox.Text);
                classCInput = int.Parse(classcTextBox.Text);
    
                totalClassA = classAInput * classA;  // Calculates the total revenues
                totalClassB = classBInput * classB;
                totalClassC = classCInput * classC;
                totalRevenue = totalClassA + totalClassB + totalClassC;
    
                classaRevenueLabel.Text = totalClassA.ToString(); //Displays totals in labels to user
                classbRevenueLabel.Text = totalClassB.ToString();
                classcRevenueLabel.Text = totalClassC.ToString();
                totalRevenueLabel.Text = totalRevenue.ToString();
    It is giving me an error on "classBInput = int.Parse(classbTextBox.Text);" line and saying Input string was not in a correct format.

    If you need any more details of this program let me know and I can list each label name etc and also provide a pic of the UI. (sorry if its confusing)
    Last edited by DataMiser; March 19th, 2012 at 09:01 AM.

  2. #2
    Join Date
    Jan 2009
    Posts
    596

    Re: Help beginner with a simple code.

    Quote Originally Posted by sync1337 View Post
    Code:
                classAInput = int.Parse(classaTextBox.Text); //Assign int values to classinputs from user input
                classBInput = int.Parse(classbTextBox.Text);
                classCInput = int.Parse(classcTextBox.Text);
    It is giving me an error on "classBInput = int.Parse(classbTextBox.Text);" line and saying Input string was not in a correct format.
    As it is having an error on the classB line, I presume it is working for classA? This indicates that the text in the classbTextBox is the problem - maybe it is not a number.

    When using int.Parse you should be aware that it may throw exceptions, and you should be prepared to handle these. The important ones in your case will be:
    FormatException - thrown if the string is not a number
    OverflowException - thrown if the string, while being a number, is too high or low to fit in an int.

    If you don't want to handle exceptions, you should use the int.TryParse method instead. This give you the int result through an out parameter, and returns a boolean to tell you whether it succeeded.

    Finally, a note on coding style. It is generally better to declare variables where they are first needed. Also, if you don't intend to change a variable after first assigning to it, declare it const. This can help prevent inadvertently changing the wrong variable due to a typo. So instead of this:
    Code:
    int classAInput;  // Creating 3 ints to hold tickets sold input
    int classBInput;
    int classCInput;
    
    double totalClassA;   // Creating 4 doubles to hold total revenue values
    double totalClassB;
    double totalClassC;
    double totalRevenue;
    
    classAInput = int.Parse(classaTextBox.Text); //Assign int values to classinputs from user input
    classBInput = int.Parse(classbTextBox.Text);
    classCInput = int.Parse(classcTextBox.Text);
    
    totalClassA = classAInput * classA;  // Calculates the total revenues
    totalClassB = classBInput * classB;
    totalClassC = classCInput * classC;
    totalRevenue = totalClassA + totalClassB + totalClassC;
    Do this:
    Code:
    const int classAInput = int.Parse(classaTextBox.Text); //Assign int values to classinputs from user input
    const int classBInput = int.Parse(classbTextBox.Text);
    const int classCInput = int.Parse(classcTextBox.Text);
    
    const double totalClassA = classAInput * classA;  // Calculates the total revenues
    const double totalClassB = classBInput * classB;
    const double totalClassC = classCInput * classC;
    const double totalRevenue = totalClassA + totalClassB + totalClassC;

  3. #3
    Join Date
    Mar 2005
    Location
    Vienna, Austria
    Posts
    4,538

    Re: Help beginner with a simple code.

    Hi !
    There arer different ways you may get an error when using that code, because in the easiest way it may happen when one of the textboxrd idt empty!!! Or if you have an entry containing an alpha- nonnumeric sign like a,b,c ...
    So to prevent tahar you have to know : In programming we have two different ways of handling inputs
    a) Errorhandling
    b) Protecting against errors
    a) simple would inform the user that he has done an error by a message when the erro gets obvious to the program
    e.g. you have three fields and want to calculate them by pressing the calculate button you may do something like
    Code:
    if ( InputChecked) {
              int a = int.Parse(txtValA.Text); 
              int b = int.Parse(txtValB.Text);
              int c  = int.Parse(txtValC.Text);
              txtResult.Text = (a+b+c).ToString(); // write to the result Textbox
     
    }
     
    private bool InputChecked(){
         if(txtValA.Text == string.Empty){
              MessageBox.Show("You need to enter some numeric Value);
              txtValA.SetFocus();         
              return false;
         }
        // The same for txtValB and txtValC
       //...: followed by
       return true;
    }
    B) You may basically use some delegate like KeyDown delegate to prevent the user to write some values into the textbox which does not fit to the purpose you want the user to do. Like you dont allow to type non numeric values into a box where only numeric values are allowed

    Its totally fine a program throws any errors if they are known by the programmer in before and correctly used to inform the user about whats going on, like messages that a value in the moment cannot be stored or something similar. Bad programming is only if you are sloppy coding by not thinking in before what may happen to the program when a user doesn't use it in the way he should.
    Jonny Poet

    To be Alive is depending on the willingsness to help others and also to permit others to help you. So lets be alive. !
    Using Code Tags makes the difference: Code is easier to read, so its easier to help. Do it like this: [CODE] Put Your Code here [/code]
    If anyone felt he has got help, show it in rating the post.
    Also dont forget to set a post which is fully answered to 'resolved'. For more details look to FAQ's about Forum Usage. BTW I'm using Framework 3.5 and you ?
    My latest articles :
    Creating a Dockable Panel-Controlmanager Using C#, Part 1 | Part 2 | Part 3 | Part 4 | Part 5 | Part 6 | Part 7

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured