I have been trying to code a program whereby the user inputs an angle, assuming it is degrees, it gets converted from degrees to radians and then calculates its sine or cosine. I tried to do this in a way which is convenient for the user but it turns out I have some issues trying to calculate both of these(cosine and sine) and outputting correct results. I appreciate your help. Also assuming constant number of terms which is 30.
import java.util.Scanner;
public class Question8 {
public static double radians(double angle)
{
double pi = 3.141592653589793238462643;
return angle / 180.0 * pi; //conversion from degrees to radians
}
public static void main( String [] args)
{
Scanner sc = new Scanner(System.in);
int sw = 0, n, j=1, m=-1;
double sine, i=0, r=0, cosine, c=0, rad; //initialising variables of type double and int
do{
System.out.println("Please input either 1 or 2 to calculate Sine or Cosine respectively.");
sw = sc.nextInt();
switch(sw) { //implementing a switch to differentiate between sine and cosine
case 1:{ //this calculates the sine
System.out.println("Please input Angle and n (number of terms) to calculate sine");
sine = sc.nextDouble();
n = sc.nextInt();
rad = radians(sine);
i = rad;
for(int k = 3; k < n; k = k+2) {
double o = Math.pow(rad,k);
j = j*(k-1)*k;
r = o/j;
i=i+m*r;
m=m*(-1);
}
System.out.println("Sine " + sine + " = " + i);
}
break;
case 2:{ //this calculates cosine
System.out.println("Please input angle and n to calculate cosine");
cosine = sc.nextDouble();
n = sc.nextInt();
rad = radians(cosine);
c = 1.0;
for(int k = 2; k < n; k = k+2) {
double o = Math.pow(rad,k);
j = j*(k-1)*k;
r = o/j;
c=c+m*r;
m = m*(-1);
}
System.out.println("Cosine " + cosine + " = " + c);
}
break;
default: {
System.out.println("Invalid choice"); //user selects invalid numbers
}
break;
}
} while(sw != 0);
}
}