Mohammad Taghi Ghandili Mohammad Taghi Ghandili - 1 month ago 7
C# Question

error in a simple C# Project

I'm new in C# (but I know something about cpp)
I started to write a simple visual C# Program.
Q1- Why Should we use "new" in our Array determination?
if we can define non-length arrays so whay we should set a size with this kind of statement : numbers = new int[10]; ?
what does "new" do?
second problem is here in the picture!
problem with a simple calculator Program

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication10 {
public partial class Form1: Form {
int[] num;
int n = 0;
int sum = 0;
int op;
/*op=1 is + , op=2 is - , op=3 is /*/
public Form1() {
InitializeComponent();
}

private void textBox1_TextChanged(object sender, EventArgs e) {

}

private void button2_Click(object sender, EventArgs e) {
num = new int[20];
num[n] = Convert.ToInt32(tb1.Text);
n++;
tb1.Text = string.Empty;
op = 1;
}

private void button1_Click(object sender, EventArgs e) {
int last = Convert.ToInt32(tb1.Text);
if (op == 1) {
for (int i = 0; i < n; i++) {
last += num[n];

}
tb1.Text = Convert.ToString(last);
}

}

}


}

Answer

Something like this for the specific error you received:

private void button1_Click(object sender, EventArgs e) {
    int last;
    try {
        last = Convert.ToInt32(tb1.Text);
        if (op == 1) {
            for (int i = 0; i < n; i++) {
                last += num[n];

            }
            tb1.Text = Convert.ToString(last);
        }
    }
    catch (FormatException ex) {
        MessageBox.Show("'" + tb1.Text + "' is in the wrong format to be converted.");
    }
}

But you will also need to fix num[n] = Convert.ToInt32(tb1.Text); in private void button2_Click using the same concept or you will run into the same problem again.

Comments