Friday 16 October 2009

Calculator Update

\\ Program by Sadat.

import java.util.*;

public class Calculator {

public static double a = 0 ;
public static double b = 0 ;
public static char c ;
public static Scanner sc = new Scanner (System.in);

public static void main (String [] args){

geValue();
}

public static void geValue() {
try {
System.out.println("Enter a number");
String k = sc.nextLine();
StringTokenizer st = new StringTokenizer (k);
a = Double.valueOf(st.nextToken());
c = st.nextToken().charAt(0);
b = Double.valueOf(st.nextToken());
getType(c);
} catch (Exception e) {
System.out.println ("Please enter a number followed by a space and give the operator and give another space and another number and press enter");
geValue();
}
}

/*public static void getValue(char c) {
try {
b = Double.valueOf(sc.nextLine());
getType (c);
} catch (Exception e){
System.out.println ("Please enter a number and press enter");
getValue (c) ;
}
}*/

public static void getValue(){
try {
String k = sc.nextLine();
if (k.equalsIgnoreCase("Exit"))
System.exit(0);
if (k.equals ("R")k.equals ("r")){
refresh ();
}
else {
StringTokenizer st = new StringTokenizer(k);
if (st.nextToken().equalsIgnoreCase("f")){
b = Double.valueOf(st.nextToken());
factorial (b);
System.out.printf ("%.3f",a);
getValue();
} else {
c = st.nextToken().charAt(0);
b = Double.valueOf(st.nextToken());
getType (c);
}
}
} catch (Exception e){
System.out.println ("Please enter a the operator followed by a space and enter a number and press enter \n or press \"R\" or \"r\"");
getValue();
}
}

public static void getType (char c){

if (c == '+'){
System.out.printf("%.3f",add ());
getValue();
}
if (c == '-'){
System.out.printf("%.3f",sub ());
getValue();
}
if (c == '*'){
System.out.printf("%.3f",mul ());
getValue();
}
if (c == '/'){
System.out.printf("%.3f",div ());
getValue();
}

}

public static double add () {
a = a+b;
return a;
}

public static double sub () {
a = a-b;
return a;
}

public static double mul () {
a = a*b;
return a;
}

public static double div () {
a = a/b;
return a;
}

public static void refresh () {
a = 0;
b = 0;
c = ' ';
geValue();
}

public static double factorial(double k){
if (k == 0)
return 1;
else {
a = (factorial((int)k-1)*k);
return a;
}
}

}

No comments:

Post a Comment