簡體   English   中英

為什么這些方法在每個數組中返回許多值而不是一個值?

[英]Why the methods returning many value instead of one in each array?

我在返回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]);
    }
  }
}

看起來您想在數組的每個位置存儲一個數字,因此您應該使用%運算符來獲取最后一個數字:

...
tab[pos]=num%10;
return Decompose(tab,pos-1,num/10);
...

您每次都將數組分配給實際數字,這就是為什么每次迭代都得到整數減一的原因。 您應該將選項卡分配更改為:

tab[pos] = num % 10;

位置也應到達索引0,因此將檢查更改為:

if (pos < 0)

暫無
暫無

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

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