C sharp - Ayuda programa c# secundaria

 
Vista:

Ayuda programa c# secundaria

Publicado por Maxi Sanchez (1 intervención) el 16/04/2016 23:23:35
Hola, en el colegio me pidieron hacer una calculadora, ya la tengo echa, pero tengo un problema a la hora de los errores y escribir las operaciones con el teclado. Puedo usar los numeros y tambien puedo borrar, pero no encuentro la forma de hacer que tambien pueda usar las operaciones . Tambien tengo problema con los errores, que si pone 2 comas le tire error, o que si clickea/apreta 2 operaciones tambien le tire error, nesecito ayuda, gracias!
Mi codigo es este por ahora=
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        float primero;
        float segundo;
        float resultado;
        string operacion;
 
 
 
        public Form1()
        {
            InitializeComponent();
        }
 
        private void btn0_Click(object sender, EventArgs e)
        {
            txtpantalla.Text = txtpantalla.Text + "0";
        }
 
        private void btn1_Click(object sender, EventArgs e)
        {
            txtpantalla.Text = txtpantalla.Text + "1";
        }
 
        private void btn2_Click(object sender, EventArgs e)
        {
            txtpantalla.Text = txtpantalla.Text + "2";
        }
 
        private void btn3_Click(object sender, EventArgs e)
        {
            txtpantalla.Text = txtpantalla.Text + "3";
        }
 
        private void btn4_Click(object sender, EventArgs e)
        {
            txtpantalla.Text = txtpantalla.Text + "4";
        }
 
        private void btn5_Click(object sender, EventArgs e)
        {
            txtpantalla.Text = txtpantalla.Text + "5";
        }
 
        private void btn6_Click(object sender, EventArgs e)
        {
            txtpantalla.Text = txtpantalla.Text + "6";
        }
 
        private void btn7_Click(object sender, EventArgs e)
        {
            txtpantalla.Text = txtpantalla.Text + "7";
        }
 
        private void btn8_Click(object sender, EventArgs e)
        {
            txtpantalla.Text = txtpantalla.Text + "8";
        }
 
        private void btn9_Click(object sender, EventArgs e)
        {
            txtpantalla.Text = txtpantalla.Text + "9";
        }
 
        private void btnpunto_Click(object sender, EventArgs e)
        {
            txtpantalla.Text = txtpantalla.Text + ",";
        }
 
        private void btnsuma_Click(object sender, EventArgs e)
        {
            operacion = "+";
            primero = float.Parse(txtpantalla.Text);
            txtpantalla.Clear();
 
 
        }
 
        private void btnresta_Click(object sender, EventArgs e)
        {
            operacion = "-";
            primero = float.Parse(txtpantalla.Text);
            txtpantalla.Clear();
        }
 
        private void btnmultiplicacion_Click(object sender, EventArgs e)
        {
            operacion = "*";
            primero = float.Parse(txtpantalla.Text);
            txtpantalla.Clear();
        }
 
        private void btndivision_Click(object sender, EventArgs e)
        {
            operacion = "/";
            primero = float.Parse(txtpantalla.Text);
            txtpantalla.Clear();
        }
 
        private void btnigual_Click(object sender, EventArgs e)
        {
            segundo = float.Parse(txtpantalla.Text);
            switch(operacion){
                case "+":
                    resultado = primero + segundo;
                    txtpantalla.Text = resultado.ToString();
                    break;
                case "-":
                    resultado = primero - segundo;
                    txtpantalla.Text = resultado.ToString();
                    break;
                case "*":
                    resultado = primero * segundo;
                    txtpantalla.Text = resultado.ToString();
                    break;
                case "/":
                    resultado = primero / segundo;
                    txtpantalla.Text = resultado.ToString();
                    break;
 
 
        }
    }
 
        private void btnlimpiar_Click(object sender, EventArgs e)
        {
            txtpantalla.Clear();
 
 
        }
 
        private void txtpantalla_TextChanged(object sender, EventArgs e)
        {
 
        }
 
        private void txtpantalla_KeyPress(object sender, KeyPressEventArgs e)
        {
            if((e.KeyChar >= (char)Keys.D0 && e.KeyChar <= (char)Keys.D9)|| (e.KeyChar==',')|| (e.KeyChar==(char)8))
            e.Handled=false;
            else
            e.Handled=true;
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

Ayuda programa c# secundaria

Publicado por Mario Amezcua (11 intervenciones) el 18/04/2016 18:12:53
Hola,

Mejoraria mucho tu implementación si implementas todo el codigo de input en un solo metodo,

En la inicializacion de tu clase, estableces los handlers de todos tus controles al mismo metodo ej:

1
2
3
4
5
6
7
public Form1()
        {
            InitializeComponent();
            btn0_Click.Click += InputsCalc;
            btn1_Click.Click += InputsCalc;
            .........
        }

Es decir todos tus botones apuntan a mismo controlador, de esta forma tambien puedes poner el mismo handler para tu textbox que estas poniendo para que el usuario capture desde el teclado :

1
txtpantalla.KeyPress+=InputsCalc

necesitas estas variables globales para llevar el acarreo y el control, estas van en la clase antes del constructor

1
2
3
4
string current, primero, segundo;
string operationRequest="",
bool doOperation = false;
bool primeroFlag=false;

despues creas el controlador

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
protected void InputsCalc(object sender, object e)
{
       //Aqui primero determinas de que tipo es "e" y determinas que operacion hay que hacer
       Keys key;
 
       if(e is System.Windows.Forms.KeyEventArgs)
       {
              var keyArgs= (System.Windows.Forms.KeyEventArgs)e;
              key=keyArgs.KeyCode
        }
        else
        {
            var button = (Button) sender;
             switch(button.Text)
             {
                  case "0":
                      key=Keys.D0;
                      break;
                  case "1"
                      key=Keys.D1;
                      break;
                  ............
              }
         }
 
         ///Determinas si estas escribiendo el primer numero o el segundo
 
         if(!primeroFlag)
                current = primero;
         else
             {
                current = segundo;
                doOperation = true;// si estas escribiendo el segundo se prende la bandera para finalizar cuando opriman =/Enter
             }
 
             //// Codigo que le dice que hacer con cada tecla
               switch(keyArgs.KeyCode){
                    case Keys.D0:
                    case Keys.NumPad0:
                         current += "0";
                         break;
                    case Keys.D1:
                    case Keys.NumPad1:
                         current += "1";
                         break;
               ..................
                    case Keys.Oemcomma:
                         if(!current.Contains(".")){ ///Verificas si ya agregaste este caracter ya que solo se permite uno
                         current += ".";
                         }
                         break;
               .................
                    case Keys.Oemplus:
                         operationRequest = "+";
                         break;
               .................
                    case Keys.Enter:
                        if(!primeroFlag)
                         {
                              primeroFlag=true;
                         }
                        else
                        if(doOperation)
                            try{
                                 var num1= float.parse(primero);
                                 var num2= float.parse(segundo);
                                 var result=0;
                                 switch(operationRequest){
                                    case "+"
                                          result=num1+num2;
                                          break;
                                    case "-"
                                          result=num1-num2;
                                          break;
                                    case "*"
                                          result=num1*num2;
                                          break;
                                    case "/"
                                          result=num1/num2;
                                          break;
                                  }
                                 primero=string.Empty;
                                 segundo=string.Empty;
                                 operationRequest=string.Empty;
                                 doOperation=false;
 
                                /// muestras el resultado
                                  txtResultado.Text=result.ToString();
                             }
                            catch
                             {
                               ///Despliega un mensaje de error si existe
                             }
 
 
               }
 
 
}


Espero que te ayude, suerte
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar