• Lenguaje

    Java usando Applet

  • Descripción

    Calculadora que suma, resta, multiplica y divide

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
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class CalculadoraQueSumaRestaMultiplicaYDivide extends Applet implements ActionListener {

    private static final long serialVersionUID = 1L;
    private TextField field_a, field_b;
    private Choice choice_operacion;
    private Label label_resultado;
    private Button button;

    @Override
    public void init() {
        field_a = new TextField(4);
        field_b = new TextField(4);
        label_resultado = new Label();
        choice_operacion = new Choice();
        choice_operacion.add("Suma");
        choice_operacion.add("Resta");
        choice_operacion.add("Multiplicaci\u00F3n");
        choice_operacion.add("Divisi\u00F3n");
        button = new Button("Procesar");
        setLayout(new BorderLayout());
        Panel panel, subpanel;
        panel = new Panel(new BorderLayout());
        subpanel = new Panel(new GridLayout(3, 1));
        subpanel.add(new Label("Ingresa el valor de a:"));
        subpanel.add(new Label("Ingresa el valor de b:"));
        subpanel.add(new Label("Selecciona el valor de operacion:"));
        panel.add(subpanel, BorderLayout.WEST);
        subpanel = new Panel(new GridLayout(3, 1));
        subpanel.add(field_a);
        subpanel.add(field_b);
        subpanel.add(choice_operacion);
        panel.add(subpanel);
        add(panel, BorderLayout.NORTH);
        panel = new Panel(new FlowLayout());
        panel.add(button);
        add(panel);
        panel = new Panel(new BorderLayout());
        subpanel = new Panel(new GridLayout(1, 1));
        subpanel.add(new Label("Valor de resultado:"));
        panel.add(subpanel, BorderLayout.WEST);
        subpanel = new Panel(new GridLayout(1, 1));
        subpanel.add(label_resultado);
        panel.add(subpanel);
        add(panel, BorderLayout.SOUTH);
        button.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent actionEvent) {
        int operacion;
        double a, b, resultado;
        try {
            a = Double.parseDouble(field_a.getText());
            b = Double.parseDouble(field_b.getText());
        } catch (NumberFormatException numberFormatException) {
            return;
        }
        operacion = choice_operacion.getSelectedIndex() + 1;
        resultado=0;
        if(operacion==1)
            resultado=a+b;
        if(operacion==2)
            resultado=a-b;
        if(operacion==3)
            resultado=a*b;
        if(operacion==4&&b!=0)
            resultado=a/b;
        label_resultado.setText(String.valueOf(resultado));
    }

}