import java.io.*;
import java.lang.*;
import java.awt.*;
import java.awt.event.*;
/*
* Простой калькулятор
*/
class Calculator extends Frame implements ActionListener{
// арифметические переменые
private char savedAction;
private boolean clear;
private float savedValue;

// переменные графического интерфейса
private TextField display;
private Panel buttonsPanel;
private Button buttons[];

public Calculator()
{
setupGUI();

// set action listener to close current window
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent ev){
System.exit(0);
}
}
);

// при нажатии кнопки с ариф.действиями в текстовом поле стирается информация
this.clear = true;
}

public Insets insets() {
return new Insets(30, 15, 15, 15) ;
}


private void setupGUI()
{
this.setLayout( new BorderLayout() );

// создание однострочной области для ввода текста
display = new TextField("0"); //создали новый объект
this.add(display, BorderLayout.NORTH); //добавили его в окно верхнего уровня


// создаем панель для кнопок
buttonsPanel = new Panel(); //создали новый объект Panel()
buttonsPanel.setLayout( new GridLayout(4,5) );//указали что панель имеет
// 4 строки и 5 столбцов
this.add( buttonsPanel, BorderLayout.CENTER );//добавили панель в центр окна

//создаем 20 кнопок

buttons = new Button[20];
for(int i=0; i<buttons.length; i++){
buttons[i] = new Button(); // создали новый объект Button()
buttons[i].addActionListener( this );
buttonsPanel.add( buttons[i] ); // добавили объект к панели
}

// подписываем кнопки с цифрами
buttons[0].setLabel("7");
buttons[1].setLabel("8");
buttons[2].setLabel("9");
buttons[5].setLabel("4");
buttons[6].setLabel("5");
buttons[7].setLabel("6");
buttons[10].setLabel("1");
buttons[11].setLabel("2");
buttons[12].setLabel("3");
buttons[15].setLabel("0");

// подписываем кнопки с действиями
buttons[3].setLabel("/");
buttons[8].setLabel("*");
buttons[13].setLabel("-");
buttons[18].setLabel("+");
buttons[17].setLabel(".");
buttons[19].setLabel("=");
buttons[4].setLabel("clear");
buttons[9].setLabel("%");
buttons[14].setLabel("sqrt");
buttons[16].setLabel("[+/-]");

//вычисляет размеры кнопок,текстовых полей
pack();
}

public void actionPerformed( ActionEvent e )
{
String str;
char cmd;

str = e.getActionCommand();
cmd = (str.toCharArray())[0];//строка превращается в массив из него берется
// первая буква

// display or calulate
if( Character.isDigit( cmd ) || cmd == '.' )
{
if( clear )
{
try{savedValue = (new Float(display.getText())).floatValue();}
catch(NumberFormatException e1){}
display.setText("");
clear = false;
}
// add new digit to display
display.setText( display.getText() + cmd );
}
else
{
calculate(cmd);
}
}

private void calculate(char cmd)
{
float curValue;
float newValue = 0;
// get current value of display
try{
curValue = (new Float(display.getText())).floatValue();
}
catch(NumberFormatException ep)
{
curValue = 0;
}

//System.out.println("savedAction="+savedAction);
if( savedAction == 0 )
{
clear = true;
savedAction = cmd;
switch(savedAction)
{
case 's':
newValue = (float)Math.sqrt( (double) curValue);
savedAction = 0;
display.setText(""+newValue);
break;
case 'c':
newValue = 0;
savedAction = 0;
display.setText(""+newValue);
break;
case '[':
newValue = - curValue;
savedAction = 0;
display.setText(""+newValue);
break;
}
}
else
{
switch(savedAction)
{
case '/':
newValue = savedValue / curValue;
break;
case '*':
newValue = savedValue * curValue;
break;
case '-':
newValue = savedValue - curValue;
break;
case '+':
newValue = savedValue + curValue;
break;
case '%':
newValue = savedValue % curValue;
break;
}

display.setText(""+newValue);
clear = true;

if( cmd == '=' )
{

savedAction = 0;
}
else
{

savedAction = cmd;
}
}
}



//запустить из командной строки
public static void main(String args[])
{
new Calculator().show();
}



}