Hi every one i just started my java class.Its been a week since the class and since i have some programming knowlage with C it want a big deal to creat it ..All my friends were impresed coz we havent even started AWT programming (win API) and i just made this here is the code ...Save it as
Calculator.java
if u have java compiler installed goto your command prompt and type javac Calculator.java
then java Calculator
Code:
/*Calculator in java*/
import java.awt.*;
import java.util.*;
import java.awt.event.*;
public class Calculator extends Frame implements ActionListener
{
public Button btn[];
public String numstr[] = {"7","8","9","/","4","5","6","*","1","2","3","-","0",".","=","+","CE"};
public TextField tf = new TextField();
Panel p2 = new Panel (new GridLayout(5,4,2,2));
String st, store ;
String str[] = new String[3];
String storestr;
float num[] = new float[2];
int sum;
int cnt=0;
StringTokenizer Tok;
public Calculator()
{
super("Calculator");
st = new String();
add("North",tf);
add("Center",p2);
p2.setBackground(Color.gray);
btn = new Button[numstr.length];
for ( int i=0; i < numstr.length; i++ ){
btn[ i ] = new Button (numstr[ i ]);
btn[ i ].addActionListener( this );
p2.add(btn[i]);
}
btn[16].setForeground(Color.red);
btn[0].setForeground(Color.blue);
btn[1].setForeground(Color.blue);
btn[2].setForeground(Color.blue);
btn[4].setForeground(Color.blue);
btn[5].setForeground(Color.blue);
btn[6].setForeground(Color.blue);
btn[8].setForeground(Color.blue);
btn[9].setForeground(Color.blue);
btn[10].setForeground(Color.blue);
btn[12].setForeground(Color.blue);
}
public void actionPerformed( ActionEvent ae )
{
store = ae.getActionCommand();
if ( store.equals("=") ){
storestr = tf.getText();
Tok= new StringTokenizer(storestr, "*+/-", true);
while( Tok.hasMoreTokens() ){
str[cnt] = Tok.nextToken();
cnt++;
}
num[0] = Float.parseFloat( str[0] );
num[1] = Float.parseFloat( str[2] );
if ( str[1].equals("*") ){
sum = (int)(num[0] * num[1]);
tf.setText(String.valueOf(sum));
}
else if ( str[1].equals("+") ){
sum =(int) (num[0] + num[1]);
tf.setText(String.valueOf(sum));
}
else if ( str[1].equals("-") ){
sum =(int)( num[0] - num[1]);
tf.setText(String.valueOf(sum));
}
else if ( str[1].equals("/") ){
sum = (int)(num[0] / num[1]);
tf.setText(String.valueOf(sum));
}
}
else if ( store.equals("CE") )
{
st = "";
store = "";
cnt = 0;
tf.setText("0");
}
else{
st += store;
tf.setText(st);
}
}
public static void main(String args[])
{
Calculator f = new Calculator();
f.setSize(200,200);
f.show();
}
}
Peace