簡體   English   中英

如何通過給出正數使用遞歸在Java中構建2d數組?

[英]How to build 2d array in Java using recursion by giving a positive number?

我有一個代碼,要求用戶輸入一個正數。

使用遞歸,系統應該顯示一個二維數組,如下所示:

如果用戶輸入數字6

輸出:

0

1 0

2 1 0

3 2 1 0

4 3 2 1 0

5 4 3 2 1 0

這是我的代碼:

package question1;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class PositiveNumber {

    public static void main(String[] args){

        int  n = 0;
        List<Integer>listofNumbers = new ArrayList<Integer>();
        Scanner sc = new Scanner(System.in);

        System.out.println("Choose a positive number");
        for(int i = 0 ; i< listofNumbers.size(); i++){
            listofNumbers.add(i);
             n = sc.nextInt();
            printInReverse(listofNumbers);
        }

    }

    public static void printInReverse(List<Integer>Listofnum){
        List temp = new ArrayList(Listofnum);
        Collections.reverse(temp);
        System.out.println(temp);
    }
}

它不顯示任何輸出。 它只是要求用戶選擇一個數字。

n = sc.nextInt()從for循環中移出,並將終止條件更改為i < n

但是,您不需要構建,復制和反轉列表-您可以簡單地使用另一個for循環。

您的列表為空,因此FOR中的條件將始終為0。您需要在進入數組之前獲得輸出,或者使用do-while

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM