Java 冰雹序列法

Java 冰雹序列法,java,sequence,Java,Sequence,这是我为冰雹序列编写的代码,但我无法让它返回我要求的结果,以下是它的说明。我觉得我的主要问题是知道在哪里以及如何保存计算出的数字 For example, nextHailstone(1) should return "1 " and nextHailstone(5) * should return "5 16 8 4 2 1 ". 这是我的密码,我绝望了,我得到的是84211而不是5168421 public static String hailstones(int n) { St

这是我为冰雹序列编写的代码,但我无法让它返回我要求的结果,以下是它的说明。我觉得我的主要问题是知道在哪里以及如何保存计算出的数字

For example, nextHailstone(1) should return "1 " and nextHailstone(5)
 * should return "5 16 8 4 2 1 ".
这是我的密码,我绝望了,我得到的是84211而不是5168421

public static String hailstones(int n) {
    String newNum = " ";
    if (n == 1)
    {
        return newNum = Integer.toString(n)+" ";
    }
    else 
    {   
    while   (n != 1 )
    {
    if (n% 2 == 0)
        {
            n = n/2;
            newNum = newNum + " " + n;

        }
    else  
        {
            n = n*3 + 1 ;
            newNum = newNum + " " + n;
        }
    }
}

return newNum = newNum + " "+ Integer.toString(n);
}

您的代码需要重新排序和简化。我建议:

public static String hailstones(int n) {
    String result = "";
    while (n != 1) {
        result += Integer.toString(n) + " ";
        if (n % 2 == 0) {
            n /= 2;
        } else {
            n = n * 3 + 1;
        }
    }
    result += "1";
    return result;
}