Калькулятор
выполнил студент группы ВТ-97а
Сименко А.Л.
Пояснения к работе:
Кроме станадартных функций: +,-,/,*, а также регистра памяти, разработанный калькулятор выполняет
такие функции, как вычисление квадратного корня (клавиша "sqrt") и возведения числа в степень (клавиша
"S"). Также по нажатию клавиши "<-" затирается предыдущий символ. По нажатию клавиши "(-)" изменяется
знак числа.
Использованы классы :
Calc расширяет Applet
docalc определяет ActionListener
String
Calculator расширяет Panel
TextField
Методы класса docalc:
public double parseDouble(String s) - преобразование строки в число типа double
private void compute() - вычисление основных действий (+ - * /)
private void foperation(char character) - обработка логики нажатий на клавиши основных действий
private void addChar(String s) - ввод сивола в текущую строку ввода
public void actionPerformed(ActionEvent e) - обработка событий от клавиш
Исходный текст
import java.awt.*;
import java.awt.event.*;
import java.lang.*;
import java.applet.*;
//=======================================================================
class Calc extends Applet
{
public void init()
{
setLayout(new BorderLayout());
Calculator Cr = new Calculator();
add("Center",Cr);
}
}
//=======================================================================
class docalc implements ActionListener
{
String str;
private static double temp = 0, i;
private static double op1 = 0, op2, op3;
private static double mem1 = 0;
private static double inputvalue = 0;
private double buff1=0;
private static char f;
private static int f1,f2;
private static int flag2=0;
private double buff=0;
private static boolean flag4=true;
private static String lastkey = "clear";
private static String str_accum = "";
private static String str_num = "";
private static String oper = null;
private static double num = 0.0;
private static double accum = 0.0;
//=======================================================================
public double parseDouble(String s)
{
double g=0.0;
long f=0;
int i=0;
int j=0;
String s1="";
String s2="";
j=s.indexOf('.');
if (j>=0)
{
System.out.println(j);
s1=s.substring(j+1);
System.out.println(s1);
f=Long.parseLong(s1,10);
System.out.println(f);
s2=s.substring(0,j);
System.out.println(s2);
i=s1.length();
System.out.println(i);
g=Math.pow(10,i);
System.out.println(g);
g=f/g;
System.out.println(g);
f=Long.parseLong(s2,10);
System.out.println(f);
return (double)(g+f);
}
return g=(double)(Long.parseLong(s));
}
//=======================================================================
private void setText(String s)
{
Calculator.disp.setText(s);
Calculator.disp.setCaretPosition(s.length());
}
private void compute()
{
if(f == '/')
inputvalue = op1/op2;
if(f == '*')
inputvalue = op1*op2;
if(f == '-')
inputvalue = op1-op2;
if(f == '+')
inputvalue = op1+op2;
if(f =='S')
{
System.out.println("here\n");
op2=num;
if(op2 == 0)
inputvalue = 1;
else
{ temp = op1;
for(i=0;i< (op2 - 1);i++)
op1 = op1 * temp;
inputvalue = op1;
}
}
String s = Double.toString(inputvalue);
str_num = s;
Calculator.disp.setText(s);
}
//=======================================================================
private void foperation(char character)
{
if(lastkey == "operation")
{ f = character;
return;
}
f2 = 1;
if(f1 == 0)
{
op1 = inputvalue;
f1 = 1;
}
else
{
op2 = inputvalue;
compute();
op1 = inputvalue;
}
lastkey = "operation";
f = character;
}
//=======================================================================
private void addChar(String s)
{
if(str_num == "0" || f2 == 1)
{
str_num = s;
f2 = 0;
}
else
{
str_num = str_num + s;
}
lastkey = "number";
Calculator.disp.setText(str_num);
}
//=======================================================================
public void actionPerformed(ActionEvent e)
{
String str = e.getActionCommand();
char w;
if ((Character.isDigit(str.charAt(0)))||(str.charAt(0)=='.'))
{
if ((str.charAt(0)=='.')&&(str_num.indexOf('.')==-1))
addChar(".");
else
if(Character.isDigit(str.charAt(0)))
addChar(str);
return;
}
if (str_num.length() >= 1)
{
try
{
num=parseDouble(str_num);
}
catch(Exception q)
{
System.out.println("Found Exception!"+q);
}
inputvalue = num;
w = str.charAt(0);
if((w == '+')||(w == '-')||(w == '*')||(w == '/'))
{
foperation(w);
return;
}
}
if (str.equals("S"))
{
f='S';
op1=num;
{
foperation(f);
return;
}
}
if (str.equals("="))
{
if(lastkey == "enter")
{ op2 = op3;
op1 = inputvalue;
}
else
{ op2 = inputvalue;
op3 = op2;
};
compute();
f1 = 0; f2 = 1;
lastkey="enter";
return;
}
if (str.equals("sqrt")) {
accum=Math.sqrt(num);
String s = Double.toString(accum);
setText(s);
str_accum = "";
f2=1;
oper = null;
}
if (str.equals("C"))
{ f = 'x';
op1 = 0;
f1 = 0;
f2 = 1;
inputvalue = 0;
str_num = "";
Calculator.disp.setText("0");
lastkey = "clear";
return;
}
if (str.equals("M+")) {
accum=num;
buff+=num;
String s = Double.toString(num);
setText(s);
f=1;
str_accum = "";
oper = null;
}
if (str.equals("MC")) {
num = 0;
buff=num;
accum=num;
String s = "0";
setText(s);
str_accum = "";
f2=1;
oper = null;
}
if (str.equals("MR")) {
Calculator.disp.requestFocus();
num=buff;
accum=num;
String s = Double.toString(num);
setText(s);
str_accum = "";
f2=1;
oper = null;
}
if (str.equals("<-"))
{ int i;
if(str_num == "0")
return;
if(str_num.length() == 1)
str_num = "0";
else
if(str_num.length() == 2 && str_num.charAt(0) == '-' )
str_num = "0";
else
if(str_num.charAt(str_num.length()-2)=='.')
str_num = str_num.substring(0,str_num.length()-2);
else
str_num = str_num.substring(0,str_num.length()-1);
Calculator.disp.setText(str_num);
return;
}
if (str.equals("(-)"))
{
if(str_num == "0" && str_num == "0.0")
return;
if(str_num.charAt(0) == '-')
str_num = str_num.substring(1,str_num.length());
else
{ String ttt = "-";
str_num = ttt + str_num;
}
Calculator.disp.setText(str_num);
return;
}
}
}
//=======================================================================
class Calculator extends Panel
{ docalc l;
// constructor
Calculator()
{
l=new docalc();
setup(l);
}
public static TextField disp = null;
//=======================================================================
private void setup(docalc dc)
{
disp = new TextField(30);
disp.setEditable(false);
disp.setBackground(Color.yellow);
disp.setForeground(Color.black);
disp.setText("0");
GridBagConstraints gbc = new GridBagConstraints();
setLayout(new GridBagLayout());
gbc.insets = new Insets(2, 2, 2, 2);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 10;
gbc.anchor = GridBagConstraints.WEST;
Panel centerPanel=new Panel();
Panel buttonPanel=new Panel();
buttonPanel.setLayout(new GridLayout(5,5,5,5));
buttonPanel.setBackground(Color.white);
centerPanel.setBackground(Color.white);
//=======================================================================
docalc buttonListener = new docalc();
Button b1 = new Button("MR");
b1.addActionListener(buttonListener);
buttonPanel.add(b1);
Button b18 = new Button("7");
b18.addActionListener(buttonListener);
buttonPanel.add(b18);
Button b19 = new Button("8");
b19.addActionListener(buttonListener);
buttonPanel.add(b19);
Button b20 = new Button("9");
b20.addActionListener(buttonListener);
buttonPanel.add(b20);
Button b16 = new Button("/");
b16.addActionListener(buttonListener);
buttonPanel.add(b16);
Button b6 = new Button("M+");
b6.addActionListener(buttonListener);
buttonPanel.add(b6);
Button b13 = new Button("4");
b13.addActionListener(buttonListener);
buttonPanel.add(b13);
Button b14 = new Button("5");
b14.addActionListener(buttonListener);
buttonPanel.add(b14);
Button b15 = new Button("6");
b15.addActionListener(buttonListener);
buttonPanel.add(b15);
Button b17 = new Button("*");
b17.addActionListener(buttonListener);
buttonPanel.add(b17);
Button b7 = new Button("MC");
b7.addActionListener(buttonListener);
buttonPanel.add(b7);
Button b8 = new Button("1");
b8.addActionListener(buttonListener);
buttonPanel.add(b8);
Button b9 = new Button("2");
b9.addActionListener(buttonListener);
buttonPanel.add(b9);
Button b10 = new Button("3");
b10.addActionListener(buttonListener);
buttonPanel.add(b10);
Button b11 = new Button("-");
b11.addActionListener(buttonListener);
buttonPanel.add(b11);
Button b5 = new Button("sqrt");
b5.addActionListener(buttonListener);
buttonPanel.add(b5);
Button b25 = new Button("0");
b25.addActionListener(buttonListener);
buttonPanel.add(b25);
Button b27 = new Button(".");
b27.addActionListener(buttonListener);
buttonPanel.add(b27);
Button b30 = new Button("(-)");
b30.addActionListener(buttonListener);
buttonPanel.add(b30);
Button b12 = new Button("+");
b12.addActionListener(buttonListener);
buttonPanel.add(b12);
Button b21 = new Button("S");
b21.addActionListener(buttonListener);
buttonPanel.add(b21);
Button b23 = new Button("C");
b23.addActionListener(buttonListener);
buttonPanel.add(b23);
Button b24 = new Button("<-");
b24.addActionListener(buttonListener);
buttonPanel.add(b24);
Button b26 = new Button("=");
b26.addActionListener(buttonListener);
buttonPanel.add(b26);
centerPanel.add(disp);
setLayout(new BorderLayout());
add("Center",centerPanel);
add("South",buttonPanel);
}
}