Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Calculator, Java

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 31

import java.awt.

*;

import java.awt.event.*;

class Calculator implements ActionListener

//Declaration of Objects

Frame f=new Frame();

Label l1=new Label("First value");

Label l2=new Label("Second value");

Label l3=new Label("Result");

TextField t1=new TextField();

TextField t2=new TextField();

TextField t3=new TextField();

Button b1=new Button("Add");

Button b2=new Button("Sub");

Button b3=new Button("Mul");

Button b4=new Button("Div");

Button b5=new Button("Cancel");

Calculator()

//Giving Coordinates

l1.setBounds(50,100,100,20);

l2.setBounds(50,140,100,20);

l3.setBounds(50,180,100,20);

t1.setBounds(200,100,100,20);

t2.setBounds(200,140,100,20);

t3.setBounds(200,180,100,20);

b1.setBounds(50,250,50,20);

b2.setBounds(110,250,50,20);
b3.setBounds(170,250,50,20);

b4.setBounds(230,250,50,20);

b5.setBounds(290,250,50,20);

//Adding components to the frame

f.add(l1);

f.add(l2);

f.add(l3);

f.add(t1);

f.add(t2);

f.add(t3);

f.add(b1);

f.add(b2);

f.add(b3);

f.add(b4);

f.add(b5);

b1.addActionListener(this);

b2.addActionListener(this);

b3.addActionListener(this);

b4.addActionListener(this);

b5.addActionListener(this);

f.setLayout(null);

f.setVisible(true);

f.setSize(400,350);

public void actionPerformed(ActionEvent e)

int n1=Integer.parseInt(t1.getText());

int n2=Integer.parseInt(t2.getText());

if(e.getSource()==b1)
{

t3.setText(String.valueOf(n1+n2));

if(e.getSource()==b2)

t3.setText(String.valueOf(n1-n2));

if(e.getSource()==b3)

t3.setText(String.valueOf(n1*n2));

if(e.getSource()==b4)

t3.setText(String.valueOf(n1/n2));

if(e.getSource()==b5)

System.exit(0);

public static void main(String...s)

new Calculator();

}}

import java.awt.event.*;

import javax.swing.*;

import java.awt.*;

class calculator extends JFrame implements ActionListener {


// create a frame

static JFrame f;

// create a textfield

static JTextField l;

// store operator and operands

String s0, s1, s2;

// default constructor

calculator()

s0 = s1 = s2 = "";

// main function

public static void main(String args[])

// create a frame

f = new JFrame("calculator");

try {

// set look and feel

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

catch (Exception e) {

System.err.println(e.getMessage());

}
// create a object of class

calculator c = new calculator();

// create a textfield

l = new JTextField(16);

// set the textfield to non editable

l.setEditable(false);

// create number buttons and some operators

JButton b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bs, bd, bm, be, beq, beq1;

// create number buttons

b0 = new JButton("0");

b1 = new JButton("1");

b2 = new JButton("2");

b3 = new JButton("3");

b4 = new JButton("4");

b5 = new JButton("5");

b6 = new JButton("6");

b7 = new JButton("7");

b8 = new JButton("8");

b9 = new JButton("9");

// equals button

beq1 = new JButton("=");

// create operator buttons

ba = new JButton("+");
bs = new JButton("-");

bd = new JButton("/");

bm = new JButton("*");

beq = new JButton("C");

// create . button

be = new JButton(".");

// create a panel

JPanel p = new JPanel();

// add action listeners

bm.addActionListener(c);

bd.addActionListener(c);

bs.addActionListener(c);

ba.addActionListener(c);

b9.addActionListener(c);

b8.addActionListener(c);

b7.addActionListener(c);

b6.addActionListener(c);

b5.addActionListener(c);

b4.addActionListener(c);

b3.addActionListener(c);

b2.addActionListener(c);

b1.addActionListener(c);

b0.addActionListener(c);

be.addActionListener(c);

beq.addActionListener(c);

beq1.addActionListener(c);
// add elements to panel

p.add(l);

p.add(ba);

p.add(b1);

p.add(b2);

p.add(b3);

p.add(bs);

p.add(b4);

p.add(b5);

p.add(b6);

p.add(bm);

p.add(b7);

p.add(b8);

p.add(b9);

p.add(bd);

p.add(be);

p.add(b0);

p.add(beq);

p.add(beq1);

// set Background of panel

p.setBackground(Color.blue);

// add panel to frame

f.add(p);

f.setSize(200, 220);

f.show();
}

public void actionPerformed(ActionEvent e)

String s = e.getActionCommand();

// if the value is a number

if ((s.charAt(0) >= '0' && s.charAt(0) <= '9') || s.charAt(0) == '.') {

// if operand is present then add to second no

if (!s1.equals(""))

s2 = s2 + s;

else

s0 = s0 + s;

// set the value of text

l.setText(s0 + s1 + s2);

else if (s.charAt(0) == 'C') {

// clear the one letter

s0 = s1 = s2 = "";

// set the value of text

l.setText(s0 + s1 + s2);

else if (s.charAt(0) == '=') {

double te;

// store the value in 1st

if (s1.equals("+"))
te = (Double.parseDouble(s0) + Double.parseDouble(s2));

else if (s1.equals("-"))

te = (Double.parseDouble(s0) - Double.parseDouble(s2));

else if (s1.equals("/"))

te = (Double.parseDouble(s0) / Double.parseDouble(s2));

else

te = (Double.parseDouble(s0) * Double.parseDouble(s2));

// set the value of text

l.setText(s0 + s1 + s2 + "=" + te);

// convert it to string

s0 = Double.toString(te);

s1 = s2 = "";

else {

// if there was no operand

if (s1.equals("") || s2.equals(""))

s1 = s;

// else evaluate

else {

double te;

// store the value in 1st

if (s1.equals("+"))

te = (Double.parseDouble(s0) + Double.parseDouble(s2));

else if (s1.equals("-"))

te = (Double.parseDouble(s0) - Double.parseDouble(s2));
else if (s1.equals("/"))

te = (Double.parseDouble(s0) / Double.parseDouble(s2));

else

te = (Double.parseDouble(s0) * Double.parseDouble(s2));

// convert it to string

s0 = Double.toString(te);

// place the operator

s1 = s;

// make the operand blank

s2 = "";

// set the value of text

l.setText(s0 + s1 + s2);

import java.awt.event.*;

import java.awt.*;

import javax.swing.*;

public class Calculator extends JFrame implements ActionListener {

JButton b10,b11,b12,b13,b14,b15;

JButton b[]=new JButton[10];

int i,r,n1,n2;

JTextField res;
char op;

public Calculator() {

super("Calulator");

setLayout(new BorderLayout());

JPanel p=new JPanel();

p.setLayout(new GridLayout(4,4));

for(int i=0;i<=9;i++) {

b[i]=new JButton(i+"");

p.add(b[i]);

b[i].addActionListener(this);

b10=new JButton("+");

p.add(b10);

b10.addActionListener(this);

b11=new JButton("-");

p.add(b11);

b11.addActionListener(this);

b12=new JButton("*");

p.add(b12);

b12.addActionListener(this);

b13=new JButton("/");

p.add(b13);

b13.addActionListener(this);

b14=new JButton("=");

p.add(b14);

b14.addActionListener(this);

b15=new JButton("C");

p.add(b15);
b15.addActionListener(this);

res=new JTextField(10);

add(p,BorderLayout.CENTER);

add(res,BorderLayout.NORTH);

setVisible(true);

setSize(200,200);

public void actionPerformed(ActionEvent ae) {

JButton pb=(JButton)ae.getSource();

if(pb==b15) {

r=n1=n2=0;

res.setText("");

} else if(pb==b14) {

n2=Integer.parseInt(res.getText());

eval();

res.setText(""+r);

} else {

boolean opf=false;

if(pb==b10) {

op='+';

opf=true;

if(pb==b11) {

op='-';

opf=true;

if(pb==b12) {

op='*';
opf=true;

if(pb==b13) {

op='/';

opf=true;

if(opf==false) {

for(i=0;i<10;i++) {

if(pb==b[i]) {

String t=res.getText();

t+=i;

res.setText(t);

} else {

n1=Integer.parseInt(res.getText());

res.setText("");

int eval() {

switch(op) {

case '+':

r=n1+n2;

break;

case '-':

r=n1-n2;

break;
case '*':

r=n1*n2;

break;

case '/':

r=n1/n2;

break;

return 0;

public static void main(String arg[]) {

new Calculator();

Rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr

import java.awt.*;

import java.awt.event.*;

/*********************************************/

public class MyCalculator extends Frame

public boolean setClear=true;

double number, memValue;

char op;

String digitButtonText[] = {"7", "8", "9", "4", "5", "6", "1", "2", "3", "0", "+/-", "." };

String operatorButtonText[] = {"/", "sqrt", "*", "%", "-", "1/X", "+", "=" };

String memoryButtonText[] = {"MC", "MR", "MS", "M+" };


String specialButtonText[] = {"Backspc", "C", "CE" };

MyDigitButton digitButton[]=new MyDigitButton[digitButtonText.length];

MyOperatorButton operatorButton[]=new MyOperatorButton[operatorButtonText.length];

MyMemoryButton memoryButton[]=new MyMemoryButton[memoryButtonText.length];

MySpecialButton specialButton[]=new MySpecialButton[specialButtonText.length];

Label displayLabel=new Label("0",Label.RIGHT);

Label memLabel=new Label(" ",Label.RIGHT);

final int FRAME_WIDTH=325,FRAME_HEIGHT=325;

final int HEIGHT=30, WIDTH=30, H_SPACE=10,V_SPACE=10;

final int TOPX=30, TOPY=50;

///////////////////////////

MyCalculator(String frameText)//constructor

super(frameText);

int tempX=TOPX, y=TOPY;

displayLabel.setBounds(tempX,y,240,HEIGHT);

displayLabel.setBackground(Color.BLUE);

displayLabel.setForeground(Color.WHITE);

add(displayLabel);

memLabel.setBounds(TOPX, TOPY+HEIGHT+ V_SPACE,WIDTH, HEIGHT);

add(memLabel);

// set Co-ordinates for Memory Buttons

tempX=TOPX;
y=TOPY+2*(HEIGHT+V_SPACE);

for(int i=0; i<memoryButton.length; i++)

memoryButton[i]=new MyMemoryButton(tempX,y,WIDTH,HEIGHT,memoryButtonText[i], this);

memoryButton[i].setForeground(Color.RED);

y+=HEIGHT+V_SPACE;

//set Co-ordinates for Special Buttons

tempX=TOPX+1*(WIDTH+H_SPACE); y=TOPY+1*(HEIGHT+V_SPACE);

for(int i=0;i<specialButton.length;i++)

specialButton[i]=new MySpecialButton(tempX,y,WIDTH*2,HEIGHT,specialButtonText[i], this);

specialButton[i].setForeground(Color.RED);

tempX=tempX+2*WIDTH+H_SPACE;

//set Co-ordinates for Digit Buttons

int digitX=TOPX+WIDTH+H_SPACE;

int digitY=TOPY+2*(HEIGHT+V_SPACE);

tempX=digitX; y=digitY;

for(int i=0;i<digitButton.length;i++)

digitButton[i]=new MyDigitButton(tempX,y,WIDTH,HEIGHT,digitButtonText[i], this);

digitButton[i].setForeground(Color.BLUE);

tempX+=WIDTH+H_SPACE;

if((i+1)%3==0){tempX=digitX; y+=HEIGHT+V_SPACE;}

}
//set Co-ordinates for Operator Buttons

int opsX=digitX+2*(WIDTH+H_SPACE)+H_SPACE;

int opsY=digitY;

tempX=opsX; y=opsY;

for(int i=0;i<operatorButton.length;i++)

tempX+=WIDTH+H_SPACE;

operatorButton[i]=new MyOperatorButton(tempX,y,WIDTH,HEIGHT,operatorButtonText[i], this);

operatorButton[i].setForeground(Color.RED);

if((i+1)%2==0){tempX=opsX; y+=HEIGHT+V_SPACE;}

addWindowListener(new WindowAdapter()

public void windowClosing(WindowEvent ev)

{System.exit(0);}

});

setLayout(null);

setSize(FRAME_WIDTH,FRAME_HEIGHT);

setVisible(true);

//////////////////////////////////

static String getFormattedText(double temp)

String resText=""+temp;

if(resText.lastIndexOf(".0")>0)

resText=resText.substring(0,resText.length()-2);

return resText;
}

////////////////////////////////////////

public static void main(String []args)

new MyCalculator("Calculator - JavaTpoint");

/*******************************************/

class MyDigitButton extends Button implements ActionListener

MyCalculator cl;

//////////////////////////////////////////

MyDigitButton(int x,int y, int width,int height,String cap, MyCalculator clc)

super(cap);

setBounds(x,y,width,height);

this.cl=clc;

this.cl.add(this);

addActionListener(this);

////////////////////////////////////////////////

static boolean isInString(String s, char ch)

for(int i=0; i<s.length();i++) if(s.charAt(i)==ch) return true;

return false;

}
/////////////////////////////////////////////////

public void actionPerformed(ActionEvent ev)

String tempText=((MyDigitButton)ev.getSource()).getLabel();

if(tempText.equals("."))

if(cl.setClear)

{cl.displayLabel.setText("0.");cl.setClear=false;}

else if(!isInString(cl.displayLabel.getText(),'.'))

cl.displayLabel.setText(cl.displayLabel.getText()+".");

return;

int index=0;

try{

index=Integer.parseInt(tempText);

}catch(NumberFormatException e){return;}

if (index==0 && cl.displayLabel.getText().equals("0")) return;

if(cl.setClear)

{cl.displayLabel.setText(""+index);cl.setClear=false;}

else

cl.displayLabel.setText(cl.displayLabel.getText()+index);

}//actionPerformed

}//class defination

/********************************************/
class MyOperatorButton extends Button implements ActionListener

MyCalculator cl;

MyOperatorButton(int x,int y, int width,int height,String cap, MyCalculator clc)

super(cap);

setBounds(x,y,width,height);

this.cl=clc;

this.cl.add(this);

addActionListener(this);

///////////////////////

public void actionPerformed(ActionEvent ev)

String opText=((MyOperatorButton)ev.getSource()).getLabel();

cl.setClear=true;

double temp=Double.parseDouble(cl.displayLabel.getText());

if(opText.equals("1/x"))

try

{double tempd=1/(double)temp;

cl.displayLabel.setText(MyCalculator.getFormattedText(tempd));}

catch(ArithmeticException excp)

{cl.displayLabel.setText("Divide by 0.");}

return;
}

if(opText.equals("sqrt"))

try

{double tempd=Math.sqrt(temp);

cl.displayLabel.setText(MyCalculator.getFormattedText(tempd));}

catch(ArithmeticException excp)

{cl.displayLabel.setText("Divide by 0.");}

return;

if(!opText.equals("="))

cl.number=temp;

cl.op=opText.charAt(0);

return;

// process = button pressed

switch(cl.op)

case '+':

temp+=cl.number;break;

case '-':

temp=cl.number-temp;break;

case '*':

temp*=cl.number;break;

case '%':

try{temp=cl.number%temp;}

catch(ArithmeticException excp)

{cl.displayLabel.setText("Divide by 0."); return;}


break;

case '/':

try{temp=cl.number/temp;}

catch(ArithmeticException excp)

{cl.displayLabel.setText("Divide by 0."); return;}

break;

}//switch

cl.displayLabel.setText(MyCalculator.getFormattedText(temp));

//cl.number=temp;

}//actionPerformed

}//class

/****************************************/

class MyMemoryButton extends Button implements ActionListener

MyCalculator cl;

/////////////////////////////////

MyMemoryButton(int x,int y, int width,int height,String cap, MyCalculator clc)

super(cap);

setBounds(x,y,width,height);

this.cl=clc;

this.cl.add(this);

addActionListener(this);

////////////////////////////////////////////////
public void actionPerformed(ActionEvent ev)

char memop=((MyMemoryButton)ev.getSource()).getLabel().charAt(1);

cl.setClear=true;

double temp=Double.parseDouble(cl.displayLabel.getText());

switch(memop)

case 'C':

cl.memLabel.setText(" ");cl.memValue=0.0;break;

case 'R':

cl.displayLabel.setText(MyCalculator.getFormattedText(cl.memValue));break;

case 'S':

cl.memValue=0.0;

case '+':

cl.memValue+=Double.parseDouble(cl.displayLabel.getText());

if(cl.displayLabel.getText().equals("0") || cl.displayLabel.getText().equals("0.0") )

cl.memLabel.setText(" ");

else

cl.memLabel.setText("M");

break;

}//switch

}//actionPerformed

}//class

/*****************************************/

class MySpecialButton extends Button implements ActionListener


{

MyCalculator cl;

MySpecialButton(int x,int y, int width,int height,String cap, MyCalculator clc)

super(cap);

setBounds(x,y,width,height);

this.cl=clc;

this.cl.add(this);

addActionListener(this);

//////////////////////

static String backSpace(String s)

String Res="";

for(int i=0; i<s.length()-1; i++) Res+=s.charAt(i);

return Res;

//////////////////////////////////////////////////////////

public void actionPerformed(ActionEvent ev)

String opText=((MySpecialButton)ev.getSource()).getLabel();

//check for backspace button

if(opText.equals("Backspc"))

String tempText=backSpace(cl.displayLabel.getText());

if(tempText.equals(""))

cl.displayLabel.setText("0");
else

cl.displayLabel.setText(tempText);

return;

//check for "C" button i.e. Reset

if(opText.equals("C"))

cl.number=0.0; cl.op=' '; cl.memValue=0.0;

cl.memLabel.setText(" ");

//it must be CE button pressed

Mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm
mmmmmmm

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class Calculator implements ActionListener{

JFrame frame;

JTextField textfield;

JButton[] numberButtons = new JButton[10];

JButton[] functionButtons = new JButton[9];

JButton addButton,subButton,mulButton,divButton;

JButton decButton, equButton, delButton, clrButton, negButton;

JPanel panel;

Font myFont = new Font("Serif",Font.BOLD,30);


double num1=0,num2=0,result=0;

char operator;

Calculator(){

frame = new JFrame("Calculator");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(420, 550);

frame.setLayout(null);

textfield = new JTextField();

textfield.setBounds(50, 25, 300, 50);

textfield.setFont(myFont);

textfield.setBackground(new Color(124,252,0));

textfield.setEditable(false);

addButton = new JButton("+");

subButton = new JButton("-");

mulButton = new JButton("*");

divButton = new JButton("/");

decButton = new JButton(".");

equButton = new JButton("=");

delButton = new JButton("Del");

clrButton = new JButton("Clr");

negButton = new JButton("(-)");

functionButtons[0] = addButton;

functionButtons[1] = subButton;
functionButtons[2] = mulButton;

functionButtons[3] = divButton;

functionButtons[4] = decButton;

functionButtons[5] = equButton;

functionButtons[6] = delButton;

functionButtons[7] = clrButton;

functionButtons[8] = negButton;

for(int i =0;i<9;i++) {

functionButtons[i].addActionListener(this);

functionButtons[i].setFont(myFont);

functionButtons[i].setFocusable(false);

for(int i =0;i<10;i++) {

numberButtons[i] = new JButton(String.valueOf(i));

numberButtons[i].addActionListener(this);

numberButtons[i].setFont(myFont);

numberButtons[i].setFocusable(false);

negButton.setBounds(50,430,100,50);

delButton.setBounds(150,430,100,50);

clrButton.setBounds(250,430,100,50);

panel = new JPanel();

panel.setBounds(50, 100, 300, 300);

panel.setLayout(new GridLayout(4,4,10,10));

panel.setBackground(new Color(124,252,0));
panel.add(numberButtons[1]);

panel.add(numberButtons[2]);

panel.add(numberButtons[3]);

panel.add(addButton);

panel.add(numberButtons[4]);

panel.add(numberButtons[5]);

panel.add(numberButtons[6]);

panel.add(subButton);

panel.add(numberButtons[7]);

panel.add(numberButtons[8]);

panel.add(numberButtons[9]);

panel.add(mulButton);

panel.add(decButton);

panel.add(numberButtons[0]);

panel.add(equButton);

panel.add(divButton);

frame.add(panel);

frame.add(negButton);

frame.add(delButton);

frame.add(clrButton);

frame.add(textfield);

frame.setVisible(true);

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

Calculator calc = new Calculator();

@Override

public void actionPerformed(ActionEvent e) {

for(int i=0;i<10;i++) {

if(e.getSource() == numberButtons[i]) {

textfield.setText(textfield.getText().concat(String.valueOf(i)));

if(e.getSource()==decButton) {

textfield.setText(textfield.getText().concat("."));

if(e.getSource()==addButton) {

num1 = Double.parseDouble(textfield.getText());

operator ='+';

textfield.setText("");

if(e.getSource()==subButton) {

num1 = Double.parseDouble(textfield.getText());

operator ='-';

textfield.setText("");

if(e.getSource()==mulButton) {

num1 = Double.parseDouble(textfield.getText());
operator ='*';

textfield.setText("");

if(e.getSource()==divButton) {

num1 = Double.parseDouble(textfield.getText());

operator ='/';

textfield.setText("");

if(e.getSource()==equButton) {

num2=Double.parseDouble(textfield.getText());

switch(operator) {

case'+':

result=num1+num2;

break;

case'-':

result=num1-num2;

break;

case'*':

result=num1*num2;

break;

case'/':

result=num1/num2;

break;

textfield.setText(String.valueOf(result));

num1=result;

if(e.getSource()==clrButton) {
textfield.setText("");

if(e.getSource()==delButton) {

String string = textfield.getText();

textfield.setText("");

for(int i=0;i<string.length()-1;i++) {

textfield.setText(textfield.getText()+string.charAt(i));

if(e.getSource()==negButton) {

double temp = Double.parseDouble(textfield.getText());

temp*=-1;

textfield.setText(String.valueOf(temp));

You might also like