我想知道是否有人可以告诉我为什么这个程序会产生它的输出。我很困惑它为什么会出现它的命令。
public class ParameterMystery{
public static void main(String[] arg) {
String p = "cause";
String q = "support";
String r = "troops";
String support = "hillary";
String cause = "rudy";
troops(p, q, r);
troops(support, p, cause);
troops(r, "p", support);
troops(q, "cause", q);
}
public static void troops(String r, String p, String q){
System.out.println(q + " gave " + r + " to the " + p);
}
}
输出结果为:
部队给予了支持 鲁迪给了希拉里这个事业 希拉里派军队到了p支持为事业提供了支持
答案 0 :(得分:0)
我认为你很困惑,因为r,p和q不匹配(他们不需要)。试试这个,看看它对你更有意义:
public static void troops(String p, String q, String r){
System.out.println(r + " gave " + p + " to the " + q);
}
或者如果您希望句子按照您发送的顺序出现:
public static void troops(String p, String q, String r){
System.out.println(p + " gave " + q + " to the " + r);
}
但在这种情况下,您需要更改方法调用,例如第一个方法调用:
troops(r, p, q);
答案 1 :(得分:0)
由于以下原因,这四条消息按此顺序出现:
troops(p, q, r);
troops(support, p, cause);
troops(r, "p", support);
troops(q, "cause", q);
如果你注意到部队方法,字符串r放在中间,字符串p在最后,字符串q在开头:
System.out.println(q + " gave " + r + " to the " + p);
这意味着如果您致电troops("1", "2", "3");
,则会输出:3 gave 1 to the 2
。
答案 2 :(得分:0)
在troop()
方法中,它首先打印最后一个(第3个)字符串(传递给方法 - q
),然后打印"gave"
,然后打印第一个字符串({{ 1}})然后r
,最后是第二个字符串。因此,混乱发生了。
它混淆了传递给方法的单词("to the"
)的顺序。
您对变量使用相同的名称,然后对值使用相同的名称,最后使用字符串。因此,有人可能很容易混淆。
例如: 第一次部队方法召唤:
您正在传递这三个值 - Strings
(但使用各自的变量名称。
然后函数首先得到第三个字符串"cause", "support", "troops"
。然后追加"troops"
,
这将生成字符串"gave"
。
然后它将追加传递的第一个字符串值 - "troops gave"
。
现在字符串是"cause"
。
然后它会附加字符串"troops gave cause"
。现在,您的字符串将为"to the"
。
最后,它附加第二个字符串 - "troops gave cause to the"
。
现在字符串已完成 - "support"
。
然后它将被打印。