如何在Java 8中合并方法重载以为一个方法名称调用不同的参数类型? [英] How do I incorporate method overloading to call different parameter types for one method name in Java 8?

查看:364
本文介绍了如何在Java 8中合并方法重载以为一个方法名称调用不同的参数类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更改代码以为一个方法名称合并一个int和double参数.我的最终目标是让用户选择两个数字,如果他们将一个数字输入为int,而将另一个数字输入为double,则我希望代码仍然能够说明这些不同的类型并成功打印.如下代码是到目前为止我已经掌握的基本知识,我想对如何更改此代码以使用方法重载提供一些帮助.

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);
 }
 }

推荐答案

您需要通过参数给出数据类型.因此,您有两种这样的方法:

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;
}

然后可以用int和double调用方法除法,然后将选择相应的方法.

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

这篇关于如何在Java 8中合并方法重载以为一个方法名称调用不同的参数类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆