Write a method that takes 3 parameters: 2 double, (num1 and num2) and 1 char (ty
ID: 2247485 • Letter: W
Question
Write a method that takes 3 parameters: 2 double, (num1 and num2) and 1 char (type), in that order, and returns a double value (rounded to two decimal places - use Math.round()) dependent on the following rules. char (type) can only be one of +, -, *, /, or %. If type is: '+' then add num1 and num2. '-' if num1 is greater than num2 then subtract num2 from num1, otherwise subtract num1 from num2. '*', then multiply num1 and num2. '/' if num2 equals zero then return 0, otherwise divide num1 by num2 '%', then return the modulo division of num1 and num2. doCalculation (3.5, 4.2, '+') rightarrow The value of the calculation is: 7.7 doCalculation (3.5, 4.2, '-') rightarrow The value of the calculation is: 0.7 doCalculation (3.5, 4.2, '*') rightarrow The value of the calculation is: 14.7 doCalculation (3.5, 4.2, '/') rightarrow The value of the calculation is: 0.83 doCalculation (3.5, 4.2, '%') rightarrow The value of the calculation is: 3.5Explanation / Answer
Below is your program: -
Calculation.java
public class Calculation {
public static double doCalculation(double num1, double num2, char c) {
double res = 0;
switch (c) {
case '+':
res = num1 + num2;
break;
case '-':
if (num1 > num2) {
res = num1 - num2;
} else {
res = num2 - num1;
}
break;
case '*':
res = num1 * num2;
break;
case '/':
if (num2 == 0) {
res = 0;
} else {
res = num1 / num2;
}
break;
case '%':
res = num1 % num2;
break;
}
res = Math.round(res * 100) / 100.0;
return res;
}
public static void main(String[] args) {
double num1 = 99.5, num2 = 534.69;
char c = '+';
System.out.println("The value of the calculation is: " + doCalculation(num1, num2, c));
System.out.println("The value of the calculation is: " + doCalculation(3.5, 4.2, '+'));
System.out.println("The value of the calculation is: " + doCalculation(3.5, 4.2, '-'));
System.out.println("The value of the calculation is: " + doCalculation(3.5, 4.2, '*'));
System.out.println("The value of the calculation is: " + doCalculation(3.5, 4.2, '/'));
System.out.println("The value of the calculation is: " + doCalculation(3.5, 4.2, '%'));
}
}
Sample run:-
The value of the calculation is: 634.19
The value of the calculation is: 7.7
The value of the calculation is: 0.7
The value of the calculation is: 14.7
The value of the calculation is: 0.83
The value of the calculation is: 3.5
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.