在下面的代码中,我写了两种方法:
test
定义为String 我在test
中有一个名为userInputhere
的变量,而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";
}
}
}
答案 0 :(得分:1)
参数名称与您调用它们不匹配的原因只有一个是参数。当你调用一个函数时,你传递了一些必须与函数所用参数的类型和数量相匹配的参数。因此,如果你有一个函数add(int x, int y)
,只要两个参数都是int
s,你调用它并不重要,当你调用函数时,它们不必被命名为x和y。
因此,函数/方法接受参数并调用函数传递参数。
答案 1 :(得分:1)
当您调用import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Test
{
public static void main(String[] args)
{
List<People> peps = new ArrayList<>();
peps.add(new People(123, "M", 14.25));
peps.add(new People(234, "M", 6.21));
peps.add(new People(362, "F", 9.23));
peps.add(new People(111, "M", 65.99));
peps.add(new People(535, "F", 9.23));
Collections.sort(peps, new People().new ComparatorId());
for (int i = 0; i < peps.size(); i++)
{
System.out.println(peps.get(i));
}
}
}
class People
{
private int id;
private String info;
private double price;
public People()
{
}
public People(int newid, String newinfo, double newprice) {
setid(newid);
setinfo(newinfo);
setprice(newprice);
}
public int getid() {
return id;
}
public void setid(int id) {
this.id = id;
}
public String getinfo() {
return info;
}
public void setinfo(String info) {
this.info = info;
}
public double getprice() {
return price;
}
public void setprice(double price) {
this.price = price;
}
class ComparatorId implements Comparator<People>
{
@Override
public int compare(People obj1, People obj2) {
Integer p1 = obj1.getid();
Integer p2 = obj2.getid();
if (p1 > p2) {
return 1;
} else if (p1 < p2){
return -1;
} else {
return 0;
}
}
}
}
方法时,其参数(Hello
)包含在Hello方法本身中。您可以将任何参数传递给message
,只要它是一个字符串(因为Hello
是String类型)。只要它解析为String,传递给message
的内容并不重要。因此,在您的示例中,变量Hello
可以正常工作,因为它是一个String。
程序实际上并没有调用“test”或调用“message”,它只调用test
方法,它可以将任何String作为参数。
答案 2 :(得分:1)
变量仅的名称在其范围内(即您可以引用它的地方) [1] 。
对于方法参数,该参数仅在该方法的主体中。
在该方法之外,唯一重要的是类型 - String
,在这种情况下。只要你传递相同类型的东西,或者可以自动转换为给定类型的类型,它就会很高兴 - 无论你怎么称呼参数(在这种情况下为message
)都会给出值无论你在参数中的那个位置传递给你的函数,每次在方法中使用该参数名称,你都将使用已赋予它的那个值(至少在你在方法中重新分配它之前,通过说{ {1}})。
您还可以执行message = ...
或Hello(input.nextLine())
之类的操作 - 无需使用临时变量。
[1]:在你开始谈论reflection之前(但不需要担心)。