Project # 4 and Calculator
Code
///Name: Tim Gibson
///Period: 6
///Project Name: Calculator
///File Name: Calculator.java
///Date Finished: 12/4/15
import java.util.Scanner;
public class Calculator
{
public static void main ( String[] args )
{
Scanner kb = new Scanner(System.in);
System.out.println( "Hello, welcome to the calculator. \nPlease input whether angles are in \"degrees\" or \"radians\"" );
String a, b, c;
boolean a1, b1, c1; //corresponds to each input
double a2, b2, c2;
a2 = 1;// they have to be initialized
a2 = 1;// they have to be initialized
b2 = 1;
c2 = 1;
do
{
System.out.print(">");
a = kb.next();
b = kb.next();
c = kb.next();
a1 = Numeric.isNumeric(a);
b1 = Numeric.isNumeric(b);
c1 = Numeric.isNumeric(c);
if ( a1 == true ) //converting everything to doubles if they're numbers
a2 = Double.parseDouble(a);
if ( b1 == true )
b2 = Double.parseDouble(b);
if ( c1 == true )
c2 = Double.parseDouble(c);
if ( a1 == false && b1 == true ) // trig functions
{
if ( a.equals("sin"))
System.out.println(sin(b2,c));
else if ( a.equals("cos"))
System.out.println(cos(b2,c));
else if ( a.equals("tan"))
System.out.println(tan(b2,c));
}
else if ( b.equals("+") && a2 != 0)
System.out.println(add(a2,c2));
else if ( b.equals("-") && a2 != 0)
System.out.println(subt(a2,c2));
else if ( b.equals("^") && a2 != 0)
System.out.println(exp(a2,c2));
else if ( b.equals("/") && a2 != 0)
System.out.println(div(a2,c2));
else if ( b.equals("*") && a2 != 0)
System.out.println(mult(a2,c2));
else if ( b.equals("!") && a2 != 0)
System.out.println(fact(a2));
else if ( a2 == 0 )
System.out.println( "Bye" );
else
System.out.println( "Error. Try Again");
} while ( a2 != 0 );
}
public static double add( double a, double b )
{
double c = a + b;
return c;
}
public static double subt( double a, double b )
{
double c = a - b;
return c;
}
public static double exp( double a, double x )//x is exponent
{
double c = 1;
for ( int n=1;n<=x;n++)
{
c*=a;
}
return c;
}
public static double div( double a, double b )
{
double c = a / b;
return c;
}
public static double mult( double a, double b )
{
double c = a * b;
return c;
}
public static double fact( double a )
{
double b = a - 1;
for ( double n = b; n > 0; n -= 1)
{
a *= n;
}
return a;
}
public static double sin( double a, String b )
{
double c = 0; //intializing c
double r; //radians
if ( b.equals("radians"))
c = Math.sin(a);
else if ( b.equals("degrees"))
{
r = ( a * Math.PI ) / 180;
c = Math.sin(r);
}
return c;
}
public static double cos( double a, String b )
{
double c = 0; //intializing c
double r; //radians
if ( b.equals("radians"))
c = Math.cos(a);
else if ( b.equals("degrees"))
{
r = ( a * Math.PI ) / 180;
c = Math.cos(r);
}
return c;
}
public static double tan( double a, String b )
{
double c = 0; //intializing c
double r; //radians
if ( b.equals("radians"))
c = Math.tan(a);
else if ( b.equals("degrees"))
{
r = ( a * Math.PI ) / 180;
c = Math.tan(r);
}
return c;
}
}
Picture of the output