How do I incorporate method overloading to call different parameter types for one method name in Java 8?

不问归期 提交于 2019-12-11 23:14:01

问题


I am trying to change my code to incorporate an int and double parameter for one method name. My end goal is to let the user pick two numbers and if they type one as int and the other as double, I want the code to still be able to account for those different types and print successfully. The code as follows is the basics I have come up with so far and I would like some help on how to change this code to use method overloading.

import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
   Scanner input = new Scanner(System.in);
    System.out.println("Select operation:");
    System.out.println("1. Divide 2 numbers");
    System.out.println("2. Exit");

    System.out.print("Enter choice(1/2:");
    int choice = input.nextInt();

    if (choice == 1){
        division();
    }
    else if (choice == 2){
        Exit();
    }
    input.close();
  }

public static void division(){
    int nOne, nTwo;
    Scanner input = new Scanner(System.in);

    System.out.println("Division");

    System.out.print("First Number: ");
    nOne = input.nextInt();

    System.out.print("Second Number: ");
    nTwo = input.nextInt();

    input.close();
    System.out.println("Sum: " + nOne + " / " + nTwo + " = " + (nOne / 
    nTwo));
 }

 public static void Exit(){
    Scanner input = new Scanner(System.in);
    System.out.println("Goodbye");
    System.exit(0);
 }
 }

回答1:


You need to give the dataype via the parameters. So you then have two methods like this:

public int division(int number1, int number2){
//do division
return result;
}

public double division(double number1, double number2){
//do division
return result;
}

you can then call the method division both with int and double and the according method will be chosen.



来源:https://stackoverflow.com/questions/53585110/how-do-i-incorporate-method-overloading-to-call-different-parameter-types-for-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!