Create a function void process(char ch, int x, int y)- to accept an arithmetic operator (+,-./, in argum
ch and two integers in arguments x and y. Now on the basis of the operator stored in ch perform the operator
in x and y and print the final result. Also, write a main function to input the two integers and an arithmetit
operator, and by invoking function process() print the output.
Example: Input:
First Integer
Second Integer
: 6
Value of ch
Output: The result of 5 and 7 on * = 24

write in java​

Respuesta :

Answer:

The program is as follows:

import java.util.*;

public class Main{

   public static void process(char ch, int x, int y){

if(ch == '+'){

    System.out.print(x+y);  }

else if(ch == '-'){

    System.out.print(x-y);  }

else if(ch == '*'){

    System.out.print(x*y);  }

else if(ch == '/'){

    if(y!=0){

        double num = x;

        System.out.print(num/y);      }

    else{

        System.out.print("Cannot divide by 0");     } }

else{

    System.out.print("Invalid operator"); }

 }

public static void main(String[] args) {

 Scanner input = new Scanner(System.in);

 int x, y;

 char ch;

 System.out.print("Enter two integers: ");

 x = input.nextInt(); y = input.nextInt();

 System.out.print("Enter operator: ");

 ch = input.next().charAt(0);  

 process(ch,x, y);

}

}

Explanation:

The function begins here

   public static void process(char ch, int x, int y){

If the character is +, this prints the sum of both integers

if(ch == '+'){

    System.out.print(x+y);  }

If the character is -, this prints the difference of both integers

else if(ch == '-'){

    System.out.print(x-y);  }

If the character is *, this prints the product of both integers

else if(ch == '*'){

    System.out.print(x*y);  }

If the character is /, this prints the division of both integers.

else if(ch == '/'){

    if(y!=0){

        double num = x;

        System.out.print(num/y);      }

    else{

This is executed if the denominator is 0

        System.out.print("Cannot divide by 0");     } }

Invalid operator is printed for every other character

else{

    System.out.print("Invalid operator"); }

}

The main begins here

public static void main(String[] args) {

 Scanner input = new Scanner(System.in);

This declares both integers

 int x, y;

This declares the operator

 char ch;

Get input for both integers

 System.out.print("Enter two integers: ");

 x = input.nextInt(); y = input.nextInt();

Get input for the operator

 System.out.print("Enter operator: ");

 ch = input.next().charAt(0);  

Call the function

 process(ch,x, y);

}

}