为什么方法在每个数组中返回多个值而不是一个?

我在 Java 中返回类型时遇到问题。该程序是关于将 5 个 chiffres 的整数分解为一个数组,而不使用预定义的方法,只使用经典算法以递归方式。我编写了代码,它与递归配合得很好,但是当我从方法中捕获新数组时,它在每种情况下都不会返回一个值,而是在一种情况下返回 2 到 5 个 chiffres。我想要实现的是:


12345 >> [1][2][3][4][5]


但我的算法给了我这个:


12345 >> [0][12][123][1234][12345]


我想问题出在返回类型或声明方法中。


这是我的代码:


public class recursive {


  static int[] Decompose (int[] tab , int pos,int num) //pos for position

  {

    if (pos == 0) //if it reach the last element of the table it stop

    {

      return tab;

    } 

    else {

      tab[pos]=num;

      return Decompose(tab,pos-1,num/10); // if we didn't reach the end continue ...    

    }


  }


  public static void main(String[] args) {

    int []t = new int[5];


    int n=12345;//the number that i want to decompose

    int pos=4;//the indicator of table position


    t=Decompose(t,pos,n);


    for (int i = 0; i < t.length; i++) {

        System.out.println(t[i]);

    }

  }

}


慕神8447489
浏览 151回答 2
2回答

隔江千里

您每次都将数组分配给实际数字,这就是为什么您在每次迭代中得到整数减一的原因。您应该将选项卡分配更改为:tab[pos]&nbsp;=&nbsp;num&nbsp;%&nbsp;10;该位置也应达到索引 0,因此将检查更改为:if&nbsp;(pos&nbsp;<&nbsp;0)

慕慕森

看起来您想在数组的每个位置存储一个数字,因此您应该使用%运算符来获取最后一个数字:...tab[pos]=num%10;return Decompose(tab,pos-1,num/10);...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java