java 拼接方法调取,如何在Java 8中合并方法重载以为一个方法名称调用不同的参数类型?...

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;

}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值