Prawo Murphy'ego: Jeżeli wydaje ci się, że już gorzej być nie może - na pewno będzie.
Część 5.4. Przykład

Na zakończenie kursu przykład użytkowego programu w Javie. Poniżej masz gotowy kod kalkulatora, który oprócz czterech podstawowych działań liczy również odwrotności liczb i pierwiastki. Analizę kodu programu przeprowadź samodzielnie. Po dokładnym przerobieniu tej części kursu nie powinno to stanowić większego problemu. Możesz po tym pokusić się o rozbudowanie kalkulatora o dodatkowe działania (np.: funkcje trygonometryczne lub ex).

import java.awt.*;
import java.awt.event.*;

public class Kalkulator extends Frame 
                     implements WindowListener, ActionListener
{ double   iTemp      = 0.0;
  char     operator   = '!';
  boolean  nowaLiczba = true;
  Label    lblWartosc = new Label("0.0", Label.RIGHT);

  public Kalkulator()
  { super ( );

    int x = 10, y = 100;
    String napisy = new String("789* 456/ 123+  0 -=");
    
    addWindowListener(this);
    setSize(265, 283);
    setResizable(false);
    setTitle("Kalkulator");
    setBackground(Color.lightGray);

    for (int i=0  ; i<20; i++)
    { if (i == 4)        { ButtonSet("1/x", x, y); }
      else if (i == 9)   { ButtonSet("sqrt", x, y); }
      else  if (i == 14) { ButtonSet("-/+", x, y); }
      else               { ButtonSet(napisy.substring(i,i+1), x, y); }
      if ((i+1) % 5 != 0 ) x += 45;
      else                 { x = 10;  y += 45; }
      if (i==14 )          { i += 3;  x += 135;}
      if ((i+1) % 5 == 3 ) { x += 20; }
    }

    Button btn = new Button("C");
    btn.setFont(new Font(null, Font.BOLD, 20));
    btn.setForeground(Color.blue);
    btn.setBounds(165,66,85,30);
    btn.addActionListener(this);
    this.add(btn);

    btn = new Button("0");
    btn.setFont(new Font(null, Font.BOLD, 20));
    btn.setForeground(Color.blue);
    btn.setBounds(10,235,85,40);
    btn.addActionListener(this);
    this.add(btn);

    btn = new Button(",");
    btn.setFont(new Font(null, Font.BOLD, 20));
    btn.setForeground(Color.blue);
    btn.setBounds(100,235,40,40);
    btn.addActionListener(this);
    this.add(btn);

    lblWartosc.setBounds(10, 30, 245, 26);
    lblWartosc.setForeground(Color.black);
    lblWartosc.setBackground(Color.white);
    lblWartosc.setFont(new Font("Serif",Font.BOLD,24));
    this.add(lblWartosc);

    setVisible(true);
  }

  void zeruj()
  { iTemp      = 0.0;
    operator   = '!';
    nowaLiczba = true;
    lblWartosc.setText("0.0");
  }

  public void actionPerformed (ActionEvent e)
  { String command = e.getActionCommand();
    String cyfry     = "0123456789";
    String dzialania = "*/+-";
    Double d;
    double d1;
    int x;

    if (command.equals("C")) 
    { zeruj(); }

    if (lblWartosc.getText().equalsIgnoreCase("###############"))
    {  return;  }

    d = new Double(lblWartosc.getText());

    if (cyfry.indexOf(command)!= -1)
    { if (!nowaLiczba)
      { if (lblWartosc.getText().length() >= 19)  return;
        if (lblWartosc.getText().equals("0.0"))
              lblWartosc.setText(command);
        else 
              lblWartosc.setText(lblWartosc.getText() + command);
      }
      else
      { lblWartosc.setText(command);
        nowaLiczba = false;
      }
    }
    else if (command.equals(","))
    { if (!nowaLiczba)
      { if (lblWartosc.getText().indexOf('.') == -1 || 
                   lblWartosc.getText().equals("0.0"))
        { if (lblWartosc.getText().equals("0.0"))
              lblWartosc.setText("0.");
          else
              lblWartosc.setText(lblWartosc.getText() + ".");
        }
      }
      else
      { lblWartosc.setText("0.");
        nowaLiczba = false;
      }
    }
    else if (command.equals("-/+"))
    { if (!lblWartosc.getText().equals("0.0"))
      { d1 = -1 * d.doubleValue();
        lblWartosc.setText(""+d1);
        if (lblWartosc.getText().indexOf('.') == -1)
            lblWartosc.setText(lblWartosc.getText().substring(0,
			           lblWartosc.getText().length()-2));
        iTemp = d1;
        nowaLiczba = true;
      }
    }
    else if (command.equals("1/x"))
    { if (d.doubleValue() == 0.0) 
      { lblWartosc.setText("###############");  }
      else
      { d1 = 1 / d.doubleValue();
        lblWartosc.setText(""+d1);
        x = lblWartosc.getText().length();
        if (lblWartosc.getText().charAt(x-2) == '.' && 
		           lblWartosc.getText().charAt(x-1) == '0')
            lblWartosc.setText(lblWartosc.getText().substring(0,
			                   lblWartosc.getText().length()-2));
        iTemp = d1;
        nowaLiczba = true;
      }
    }
    else if (command.equals("sqrt"))
    { d1 = d.doubleValue();
      if (d1 < 0)
      { lblWartosc.setText("###############");  }
      else
      { d1 = Math.sqrt(d1);
        lblWartosc.setText(""+d1);
        x = lblWartosc.getText().length();
        if (lblWartosc.getText().charAt(x-2) == '.' && 
		           lblWartosc.getText().charAt(x-1) == '0')
            lblWartosc.setText(lblWartosc.getText().substring(0,
			                   lblWartosc.getText().length() - 2));
        iTemp = d1;
        nowaLiczba = true;
      }
    }
    else if (command.equals("=") && operator != '!' && !nowaLiczba)
    {	d1 = d.doubleValue();
      switch (operator)
      { case '+':      iTemp += d1;    break;
        case '*':      iTemp *= d1;    break;
        case '-':      iTemp -= d1;    break;
        case '/':      iTemp /= d1;    break;
      }
      if (d1 == 0 && operator == '/')
      { lblWartosc.setText("###############");
      }
      else
      { lblWartosc.setText(""+iTemp);
        x = lblWartosc.getText().length();
        if (lblWartosc.getText().charAt(x-2)=='.' &&
                   lblWartosc.getText().charAt(x-1)=='0')
              lblWartosc.setText(lblWartosc.getText().substring(0,
                                 lblWartosc.getText().length()-2));
      }
      nowaLiczba = true;
      operator   = '!';
    }
    else if (dzialania.indexOf(command)!= -1)
    {	if (operator != '!' && !nowaLiczba)
      { d1 = d.doubleValue();
        switch (operator)
        { case '+':      iTemp += d1;    break;
          case '*':      iTemp *= d1;    break;
          case '-':      iTemp -= d1;    break;
          case '/':      iTemp /= d1;    break;
        }
        if (d1 == 0 && operator == '/')
        { lblWartosc.setText("###############");
        }
        else
        { lblWartosc.setText(""+iTemp);
          x = lblWartosc.getText().length();
          if (lblWartosc.getText().charAt(x-2) == '.' && 
		             lblWartosc.getText().charAt(x-1) == '0')
              lblWartosc.setText(lblWartosc.getText().substring(0,
                                 lblWartosc.getText().length()-2));
        }
      }
      else if (operator == '!')
      { iTemp = d.doubleValue();
      }
      operator = command.charAt(0);
      nowaLiczba = true;
    }
  }

  void ButtonSet (String sTxt, int x, int y)
  { Button btnX = new Button(sTxt);

    btnX.setFont(new Font(null, Font.BOLD, 20));
    btnX.setForeground(Color.blue);
    btnX.setBounds(x,y,40,40);
    btnX.addActionListener(this);
    this.add(btnX);
  }

  public static void main (String args[])
  {	
    new Kalkulator();
  }

  public void windowClosing    (WindowEvent e) { System.exit(0); }
  public void windowClosed     (WindowEvent e) {   }
  public void windowOpened     (WindowEvent e) {   }
  public void windowIconified  (WindowEvent e) {   }
  public void windowDeiconified(WindowEvent e) {   }
  public void windowActivated  (WindowEvent e) {   }
  public void windowDeactivated(WindowEvent e) {   }
}

A tak wygląda uruchomiony program:

I na tym zakończymy kurs wprowadzający do programowania w Javie...

Teraz pozostaje Ci już tylko próbować własnych sił w kolejnych programach. I co ważne: miej zawsze pod ręką dokumentację. Bez niej trudno jest zapanować nad wszystkimi klasami, ich polami i metodami...
« wstecz   dalej »