提问人:stupidmoron 提问时间:10/1/2022 更新时间:10/1/2022 访问量:47
递归数组遍历:相同的代码,不同的结果
Recursive array traversing: same code, different results
问:
我有两个以递归方式遍历数组的短程序。第一个数组向后打印数组,第二个数组向前打印数组。第二个应该向后打印数组。为什么是向前打印?这是相同的代码!!
方案一:
public class SomeClass2 {
public static String someMethod(int[] array2, int x) {
if (x < array2.length)
return String.format("%s%d ", someMethod(array2, x + 1), array2[x]);
else
return "";
}
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
String results = someMethod(array, 0);
System.out.println(results);
}
}
计划二:
import java.util.Scanner;
public class BackwardsArray {
public static String reverse(char[] array, int x) {
if (x < array.length)
return String.format("%s " + reverse(array, x + 1), array[x]);
else
return "";
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = input.nextLine();
char[] charArray = sentence.toCharArray();
String backwardsSentence = reverse(charArray, 0);
System.out.println(backwardsSentence);
}
}
答: 暂无答案
评论