我真的坚持理解这一概念。我从一次考试中抽出了一段时间,尽管我知道打印什么,但我也不知道为什么。
代码如下:
class Test {
public static void xMethod(int length) {
while (length > 1){
System.out.print((length - 1) + " ");
xMethod(length-1);
}
}
public static void main(String[] args){
xMethod(5);
}
}
答案 0 :(得分:3)
因为length
从未更新。
while (length > 1){
System.out.print((length - 1) + " ");
xMethod(length - 1);
length--;
}
答案 1 :(得分:2)
正如其他答案指出的那样,您需要减少length
变量以解决length = length - 1
或length--
当前的问题。 (我让我的“同事”回答更好地解释它。)
我的答案主要是关于您使用递归方法的。
您可能想要的只是一个简单的if
条件。递归将充当循环。
public static void xMethod(int length) {
length--;
System.out.print((length) + " ");
if (length > 1){
xMethod(length);
}
}
xMethod(5)> 4 3 2 1
public static void xMethod(int length) {
length--;
if (length > 1){
xMethod(length);
}
System.out.print((length) + " ");
}
xMethod(5)> 1 2 3 4
答案 2 :(得分:0)
长度完全不变
class Test {
public static void xMethod(int length) {
while (length > 1){
System.out.print((length - 1) + " ");
xMethod(length-1);
//need to change the length here
}
}
public static void main(String[] args){
xMethod(5);
}
答案 3 :(得分:0)
要在此处添加的重要内容是了解赋值如何在Java中工作。
length
的值不会更改,因为当您在方法中传递一个值并将其放入while
循环时,该循环将在条件停止但递归{{1}停止时停止}您已经使用过。这就是为什么即使添加xMethod(length-1);
也不会打印您想要的内容的原因。
因此,要使程序正常运行,您必须
length--
变量https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html
浏览完链接后,您将了解为什么值没有变化。
注意:从链接中您可以了解到length
等于length--
,因此基本上我们必须将更新后的值分配给length = length -1
变量
答案 4 :(得分:-1)
length始终具有值5。您应将length-1替换为length-。
class Test {
public static void xMethod(int length) {
while (length > 1){
System.out.print((length--) + " ");
xMethod(length);
}
}
public static void main(String[] args){
xMethod(5);
}
}