gpt4 book ai didi

java - Java 中的重载方法?

转载 作者:行者123 更新时间:2023-12-01 09:40:12 25 4
gpt4 key购买 nike

我对 Java 还是有点陌生​​,我需要一些关于这段代码的帮助,到目前为止我写了这些方法以及每个方法应该做什么,但老实说我不知道​​如何实现重载效果并使其工作所以我希望能得到一个简单的解释。

import java.util.Scanner;
public class Assignment3 {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
myMethod();
}
public static void myMethod(){
System.out.println("Welcome to Java 1 ");

}
public static void myMethod(String msg, int counter){
System.out.println("Enter your custom messege please: ");
msg = input.nextLine();

System.out.println("Please enter how many times do you wish to print the messsege: ");
counter = input.nextInt();

for (int i = 0; i <= counter; i++){
System.out.println(msg);
}
}
public static void myMethod(int lowerLimit, int upperLimit){

System.out.println("Please enter a lowerlimit: ");
lowerLimit = input.nextInt();

System.out.println("Please enter an upperlimit: ");
upperLimit = input.nextInt();

System.out.println("Press 1 for ascending order: ");
System.out.println("Press 2 for descending order: ");
System.out.println("Make your selection");
int user1 = input.nextInt();
System.out.println("How frequent do you wish the messege to be printed");
int interval = input.nextInt();

switch(user1){
case 1:
for(int counter = lowerLimit; counter <= upperLimit; counter += interval){
System.out.println(counter);
}
break;
case 2:
for(int counter = upperLimit; counter <= lowerLimit; counter -= interval){
System.out.println(counter);
}
break;
default :
System.out.println("Something went wrong !!!");
}

}
public static void myMethod(double number1, double number2){

number1 = (Math.random() * 100);
number2 = (Math.random() * 100);
double product = (number1 * number2);

System.out.println("The product of " + number1 + " and " + number2 + " is " + product);
}
]

最佳答案

您的 myMethod 方法已重载。重载方法只是可以接受两个或多个不同参数集的方法。 (参见https://docs.oracle.com/javase/tutorial/java/javaOO/methods.html)

例如:

public void foo(int a) {
System.out.println("Printing out the int " + a);
}

public void foo(double a) {
System.out.println("Printing out the double " + a);
}

Foo 有两种可能的参数集,一种接受 int,另一种接受 double。现在,如果你这样做:

int a = 10;
double b = 10.5;

foo(a);
foo(b);

它将返回:

Printing out the int 10
Printing out the double 10.5

关于java - Java 中的重载方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38517489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com