我有一个程序,通过给出一个正数来构建二维数组,并以递归方式显示结果,如下例所示:
n = 6 ...其中n是正数nbumber
结果将显示这个2d数组:
0
1 0
2 1 0
3 2 1 0
4 3 2 1 0
5 4 3 2 1 0
任何人都可以帮助我获得这个结果吗?
这是我开始的代码:
public class positiveNumber{
public static void main(String[] args){
for(int i = 0 i<= 6 i++){
{
for(int j = 0 j <= 6 j++){
if(i == j){
{
}
}
}
}
答案 0 :(得分:0)
尝试在列表中添加数字,并按相反的顺序在每次迭代中打印列表
public class positiveNumber{
public static void main(String[] args){
int n= taking Input from user;
List<Integer> listOfNumbers=new ArrayList<Integer>();
for(int i = 0 ; i< n ; i++){
listOfNumbers.add(i);
printListInReverse(listOfNumbers);
}
}
public static void printListInReverse(List<Integer>listOfNumbers){
List temp = new ArrayList(listOfNumbers);
Collections.reverse(temp);
System.out.println(temp); //either iterate the list or print in once
}
}
<强>输出强>
[0]
[1, 0]
[2, 1, 0]
[3, 2, 1, 0]
[4, 3, 2, 1, 0]
[5, 4, 3, 2, 1, 0]
如果要删除这些 [] 括号,则不要直接打印列表,而是使用Iterator迭代列表,然后打印列表中的每个元素
<强>更新强>
与递归
相同的程序public class positiveNumber{
static List<Integer> listOfNumbers=new ArrayList<Integer>();
static int n;
public static void main(String[] args){
n= "take input fmo user"
print(0);
}
/*
*Using Recursion
*/
public static void print(int i){
if(i==n)
return;
listOfNumbers.add(i);
printListInReverse();
print(i+1);
}
public static void printListInReverse(){
List temp = new ArrayList(listOfNumbers);
Collections.reverse(temp);
System.out.println(temp); //either iterate the list or print in once
}
}
答案 1 :(得分:0)
尝试类似:
public static void main(String args[]) {
int[][] numbers = new int[6][6];
displayPyramid(6, numbers);
System.out.println("2d array is");
for (int i = 0; i < 6; i++)
System.out.println(Arrays.toString(numbers[i]));
}
private static void displayPyramid(int next, int[][] numbers) {
if (next == 0) {
return;
}
StringBuilder sb = new StringBuilder();
for (int i = numbers[0].length - next, k = 0; i >= 0; i--) {
numbers[numbers[0].length - next][k++] = i;
sb.append(i);
sb.append(" ");
}
System.out.println(sb);
displayPyramid(next - 1, numbers);
}
Output:
0
1 0
2 1 0
3 2 1 0
4 3 2 1 0
5 4 3 2 1 0
2d array is
[0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0]
[2, 1, 0, 0, 0, 0]
[3, 2, 1, 0, 0, 0]
[4, 3, 2, 1, 0, 0]
[5, 4, 3, 2, 1, 0]