1

First time posting here sorry about the format.

public static void main(String args[]) {

        float x, y, z;
          System.out.println("Enter two integers to calculate their sum ");
          Scanner in = new Scanner(System.in);
          x = in.nextFloat();
          y = in.nextFloat();
          z = x + y;
          System.out.println("Sum of entered integers = "+z);
       }




public static void main1(String args[]) {

    int x, y, z;
      System.out.println("Enter two integers to calculate their sum ");
      Scanner in = new Scanner(System.in);
      x = in.nextInt();
      y = in.nextInt();
      z = x + y;
      System.out.println("Sum of entered integers = "+z);
   }

}

I need help method overloading on letting my program add numbers with int and floating point for example 4 and 5 = 9

4.0 and 5.0 = 9.0

but as of now my output is only giving me floating point value even if I just input number with int values.

Imran
  • 429
  • 9
  • 23

2 Answers2

1

Your main method stores the inputs and the sum in float variables, which is why the sum is also float.

Your other method main1, which accepts int inputs is not used.

If you want overloaded methods, one for ints and one for floats, you should have a single main method that would call the overloaded method (let's call it sum).

public static int sum (int x, int y)
{
    return x+y;
}

public static float sum (float x, float y)
{
    return x+y;
}

However, the method that will be called depends on the arguments that you pass to it. Therefore, if you use nextFloat to get the input, the sum (float x,float y) method will always be called, even if the user inputs integers.

public static void main(String args[]) 
{
  float x, y, z;
  System.out.println("Enter two integers to calculate their sum ");
  Scanner in = new Scanner(System.in);
  x = in.nextFloat();
  y = in.nextFloat();
  z = sum (x,y); // this will always call sum (float x, float y)
  System.out.println("Sum of entered integers = "+z);
}
Eran
  • 387,369
  • 54
  • 702
  • 768
1

When you run the class main function is executed first(if you dont have static block etc) by JVM and as you din't call main1() only main() is executed giving you float value.

Note:Overloading means two methods or more with the same name but with different parameters

But you have different method name with same arguments.

So to achieve overloading use same name for both functions and with different type or number of arguments.

In order to overload main() you can overload it but when you run class by java ClassName it will call only the main method with String array arguments main(String[] arg).You can overload main() further with your code by calling it with different arguments.

Java Docs

singhakash
  • 7,891
  • 6
  • 31
  • 65