You are here: Home / Topics / Create a method named calc, which accepts an integer (int), a character (char) and one more integer (int), and depending on the character, returns the result

Create a method named calc, which accepts an integer (int), a character (char) and one more integer (int), and depending on the character, returns the result

Filed under: Java on 2024-02-27 13:59:41

Create a method named calc, which accepts an integer (int), a character (char) and one more integer (int), and depending on the character, returns the result of the corresponding operation on numbers:

'+' — sum of integers
'-' — integer difference (first minus second)
'*' — product of integers
'/' — integer division (divide the first by the second)


If the passed character does not match those listed above, then the method should return 0.

The calc method must be public and static, with a void return type.

Method main is not involved in testing.

Requirements:
Solution class must have a public static calc(int, char, int) method, which returns an int.
calc(int, char, int) method must return a result according to task conditions.

 

Code: 


public class Solution {
   public static int calc(int num1, char c, int num2){
       switch(c){
           case '+':
               return num1+num2;
       
           case '-':
               return num1-num2;
              
           case '*':
               return num1*num2;
              
           case '/':
               return num1/num2;
              
           default:
               return 0;
       }
   }
   public static void main(String[] args) {
       System.out.println(calc(1, '+', 2));
       System.out.println(calc(5, '-', 3));
       System.out.println(calc(2, '*', 3));
       System.out.println(calc(20, '/', 5));
   }
}

 

Output:

3
2
6
4

About Author:
J
Java     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.