在下面的代码中,我编写了两个方法:
- 将变量
test
定义为字符串 - 根据输入的内容返回两种不同的结果
我在 userInputhere
中有一个名为 test
的变量,而 Hello
中的参数名为 message
。在 userInputhere
中,我使用 test
而不是 message
- 为什么这有效?
调用Hello
方法时,参数不重要吗?
我知道,当输入返回某些内容的方法时,必须定义它,并且参数进一步定义该方法将要执行的操作,因此,我假设,当从另一个方法调用所述方法时,您会必须使用相同的参数,但情况似乎并非如此。
import java.util.Scanner;
public class methodsandparameters {
static Scanner input = new Scanner(System.in);
public static void main(String[] args){
userInputhere();
}
public static void userInputhere(){
String test = input.nextLine();
System.out.println(Hello(test));
}
public static String Hello(String message){
if (message.equalsIgnoreCase("Hi")) {
return "Hello";
} else {
return "Goodbye";
}
}
}
最佳答案
当您调用 Hello
方法时,其参数(message
)包含在 Hello 方法本身内。您可以将任何参数传递给 Hello
,只要它是字符串即可(因为 message
是 String 类型)。只要解析为字符串,传递给 Hello
的内容并不重要。因此,在您的示例中,变量 test
工作正常,因为它是一个字符串。
程序实际上并没有调用“test”或调用“message”,它只是调用Hello
方法,该方法可以接受任何字符串作为参数。
关于java - 调用方法时不需要使用相同的参数名称吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31593927/