I am having a trouble with Method Overloading I was ask to create a program that will enter an operator and 2 operands. Overload the method named getAnswer as follows: -
- get its sum by calling the method
- get its difference by calling the method and pass the operands on that method.
- get its product by calling the method and returns a value.
- get its quotient by calling a method and returns a value and pass the operands on that method.
Here's my code:
import java.util.Scanner;
public class MethodHomework2
{
int a, b;
public void getAnswer()
{
int sum = a + b;
System.out.println("The sum is: " + sum);
}
public void getAnswer(int a, int b)
{
int diff = a - b;
System.out.println("The difference is: " + diff);
}
public int getAnswer()
{
int prod = a * b;
return prod;
}
public int getAnswer(int a, int b)
{
int quot = a / b;
return quot;
}
public static void main (String args[])
{
MethodHomework2 mh = new MethodHomework2();
Scanner kb = new Scanner(System.in);
int returnValue;
System.out.print("Enter 2 number: ");
a = kb.nextInt();
b = kb.nextInt();
mh.getAnswer();
mh.getAnswer(c, d);
returnValue = mh.getAnswer();
System.out.println("The product is: " + returnValue);
returnValue = mh.getAnswer(c, d);
System.out.println("The quotient is: " + returnValue);
}
}
getAnswer ()- how would it know which one to use?getAnswer()for diff andgetAnswer()for quot is not the way overloading is done as they both have same signature