Anda di halaman 1dari 11

Write a Java program that works as a simple calculator.

Use a grid
layout to arrange buttons for the digits and for the + * %
operations. Add a text field to display the result.

Source Code:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="Cal" width=300 height=300>
</applet>
*/
public class Cal extends Applet
implements ActionListener
{
String msg=" ";
int v1,v2,result;
TextField t1;
Button b[]=new Button[10];
Button add,sub,mul,div,clear,mod,EQ;
char OP;
public void init()
{
Color k=new Color(120,89,90);
setBackground(k);
t1=new TextField(10);

GridLayout gl=new GridLayout(4,5);


setLayout(gl);
for(int i=0;i<10;i++)
{
b[i]=new Button(""+i);
}
add=new Button("add");
sub=new Button("sub");
mul=new Button("mul");
div=new Button("div");
mod=new Button("mod");
clear=new Button("clear");
EQ=new Button("EQ");
t1.addActionListener(this);
add(t1);
for(int i=0;i<10;i++)
{
add(b[i]);
}
add(add);
add(sub);
add(mul);
add(div);
add(mod);
add(clear);
add(EQ);
for(int i=0;i<10;i++)
{
b[i].addActionListener(this);
}
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
char ch=str.charAt(0);
if ( Character.isDigit(ch))

t1.setText(t1.getText()+str);
else
if(str.equals("add"))
{
v1=Integer.parseInt(t1.getText());
OP='+';
t1.setText("");
}
else if(str.equals("sub"))
{
v1=Integer.parseInt(t1.getText());
OP='-';
t1.setText("");
}
else if(str.equals("mul"))
{
v1=Integer.parseInt(t1.getText());
OP='*';
t1.setText("");
}
else if(str.equals("div"))
{
v1=Integer.parseInt(t1.getText());
OP='/';
t1.setText("");
}
else if(str.equals("mod"))
{
v1=Integer.parseInt(t1.getText());
OP='%';
t1.setText("");
}
if(str.equals("EQ"))
{
v2=Integer.parseInt(t1.getText());
if(OP=='+')
result=v1+v2;
else if(OP=='-')
result=v1-v2;
else if(OP=='*')
result=v1*v2;
else if(OP=='/')
result=v1/v2;
else if(OP=='%')

result=v1%v2;
t1.setText(""+result);
}
if(str.equals("clear"))
{
t1.setText("");
}
}
}

Designing Part
import java.applet.*;
import java.awt.*;
public class KeyPad1 extends Panel
{
TextField display;
// Readout
Panel keys;
// Key Pad
int maxLength = 20;
String output = "0";
//

// Max length of Readout


// String to be displayed in
the readout

boolean decimal = false;


// Has the user inserted a decimal
// into the display, yet? (Only
// one allowed in a valid number)
float result=0.0f;
String function="";

// Result of calc.
// Function currently being performed

boolean newNumber = true; // Ready to start a new number?


boolean finished = false;
// Finished with current calc. ?
// (When "=" key pressed)
boolean memory = false;
float memoryValue = 0.0f;

// Is there a number in memory?


// Value being held in memory

public KeyPad1()
{
setLayout( new BorderLayout() );
setFont( new Font("Helvetica", Font.PLAIN, 12) );
setBackground(Color.lightGray);
display = new TextField(maxLength+1);
display.setEditable(false);
display.setFont( new Font("Helvetica", Font.PLAIN, 12) );
display.setBackground(Color.white);
keys = new Panel();
keys.setLayout( new GridLayout(5,5) );
keys.setFont( new Font("Helvetica", Font.PLAIN, 12) );
keys.setBackground(Color.lightGray);
keys.add(
keys.add(
keys.add(
keys.add(
keys.add(

new
new
new
new
new

Button("+/-") );
Button("") );
Button("") );
Button("") );
Button("AC") );

keys.add(
keys.add(
keys.add(
keys.add(
keys.add(

new
new
new
new
new

Button("M+") );
Button("7") );
Button("8") );
Button("9") );
Button("/") );

keys.add(
keys.add(
keys.add(
keys.add(
keys.add(

new
new
new
new
new

Button("M-") );
Button("4") );
Button("5") );
Button("6") );
Button("x") );

keys.add(
keys.add(
keys.add(
keys.add(
keys.add(

new
new
new
new
new

Button("MR") );
Button("1") );
Button("2") );
Button("3") );
Button("-") );

keys.add( new Button("MC") );


keys.add( new Button("0") );

keys.add( new Button(".") );


keys.add( new Button("=") );
keys.add( new Button("+") );
add("North", display);
// Readout
add("Center", new Label(""));
// Blank Space
add("South", keys);
// Number Pad
display.resize( display.preferredSize() );
keys.resize( keys.preferredSize() );
updateDisplay();

// Call my display function

show();
} // End init()
public void updateDisplay()
{
String output_right = "";

// Right Justify the Readout

for(int i=1; i<=(maxLength-output.length()); i++)


{
if ((i==1) && (memory))
output_right = output_right + "M";
else
output_right = output_right + "_";
}
output_right = output_right + output;
display.setText(output_right);
} // End updateDisplay
public void appendDigit(String new_d)
{
if (output == "0")
// If numbers are added, we don't
output = "";
// want to maintain the leading 0
if (output.length() < maxLength)
{
if (newNumber)
// If starting a new number
{
output = new_d;
// Make this the first digit
newNumber = false;
// (then it is no longer new)
}
else
output = output + new_d;
// Else just add another
updateDisplay();
}

// Print display, right justified

if (finished || function == "") // If the last calculation was finished, then by


{
// entering a new digit, we have started a new
// calculation
result = Float.valueOf(output).floatValue();
finished = false;
function = "";
}
} // End appendDigit()
public void key_equals()
{
evaluate();
function = "";
newNumber = true;
decimal = false;
finished = true;
} // End =

// Reset for a new number

public void evaluate()


{
// Perform current function
if (function == "plus")
result += Float.valueOf(output).floatValue();
else
if (function == "minus")
result -= Float.valueOf(output).floatValue();
else
if (function == "times")
result *= Float.valueOf(output).floatValue();
else
if (function == "div")
result /= Float.valueOf(output).floatValue();
else
result = Float.valueOf(output).floatValue();
if (finished == true)
should
finished = false;

// If "=" pressed, setting finished to "true," and we


// then receive another function key press, we
// continue working our last result

// And reset for a new number


output = Float.toString(result);
updateDisplay();
newNumber = true;
decimal = false;
} // End evaluate()
public boolean handleEvent(Event evt)

{
if (evt.arg == "AC")
{
result = 0;
output = Float.toString(result);
function = "";
newNumber = true;
decimal = false;
finished = true;

// Reset for a new number/function

updateDisplay();
}
if (evt.arg == "+/-")
{
// Flip sign of displayed number
float val = Float.valueOf(output).floatValue();
val *= -1;
output = Float.toString(val);
updateDisplay();
}
if
if
if
if
if
if
if
if
if
if

(evt.arg == "1") appendDigit("1");


(evt.arg == "2") appendDigit("2");
(evt.arg == "3") appendDigit("3");
(evt.arg == "4") appendDigit("4");
(evt.arg == "5") appendDigit("5");
(evt.arg == "6") appendDigit("6");
(evt.arg == "7") appendDigit("7");
(evt.arg == "8") appendDigit("8");
(evt.arg == "9") appendDigit("9");
(evt.arg == "0")
if (output.length() != 0) appendDigit("0");

if (evt.arg == ".")
if (output.length() < maxLength)
if (!decimal)
{
decimal = true;
if (output.length() == 0 || newNumber)
{
output = "0.";
newNumber = false;
}
else
output = output + ".";
updateDisplay();
}

// Print display, right justified

if (evt.arg == "=")
key_equals();
if (evt.arg == "+")
{
evaluate();
function = "plus";
}
if (evt.arg == "-")
{
evaluate();
function = "minus";
}
if (evt.arg == "x")
{
evaluate();
function = "times";
}
if (evt.arg == "/")
{
evaluate();
function = "div";
}

// Evaluate and print results

// Clean up last calculation


// and set up for new one

// Clean up last calculation


// and set up new one

// Clean up last calculation


// and set up new one

// Clean up last calculation


// and set up new one

if (evt.arg == "M+")
{
memory = true;
key_equals();

// Flag our memory value


// Update result as if "=" has been pressed
// and store the result in memory
memoryValue += Float.valueOf(output).floatValue();
updateDisplay();

}
if (evt.arg == "M-")
{
memory = true;
key_equals();

// Flag our memory value


// Update result as if "=" has been pressed
// and store the result in memory
memoryValue -= Float.valueOf(output).floatValue();
updateDisplay();

}
if (evt.arg == "MR")
{
if (memory)
{
output = Float.toString(memoryValue);

updateDisplay();
}
}
if (evt.arg == "MC")
{
memory = false;
memoryValue = 0.0f;
updateDisplay();
}
if (output == "")
output = "0";

// If no numbers are added, we can


// replace the lone 0

return false;
} // End handleEvent
} // Applet

APPLET CLASS
import java.applet.*;
import java.awt.*;

public class Calc1 extends Applet


{
Frame window;
public void init()
{
window = new Frame();

// Create a new frame

window.setTitle( "JavaCalc" );
// Set its title
window.setLayout( new FlowLayout() );
// Use FlowLayout
window.setFont( new Font("Helvetica",Font.PLAIN,12) );
window.setBackground(Color.white);
window.add( new KeyPad1() );
window.resize( window.preferredSize() );
window.pack();
window.show();
} // init()

// And drop in the calculator

} // Applet
/* <applet code="Calc1" height=400 width=400 ></applet> */

-------------------------- +++++++++++++++
------------------------------------------

Anda mungkin juga menyukai