添加int A加上单个数字A的乘积

时间:2015-03-09 01:39:03

标签: java parseint

好的,所以我正在编写一个程序,要求用户输入两个数字。

n = the starting number of a sequence.
k = the length of the sequence.

我希望下一个数字等于之前的数字加上该数字的数字的乘积。

这就是我所拥有的。我想使用parseInt,但不知道如何

public class John

{

    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int initial_num, output_seq;

        while(true)
        {
            System.out.print("Enter n and k: ");
            initial_num = sc.nextInt();
            output_seq = sc.nextInt();

            if(initial_num != 0 || output_seq != 0)
                System.out.println(nextNum(initial_num, output_seq));
            else
                break;
        }
    }

    static int nextNum(int input, int output)
    {
        int first = input;
        int seq_num = output;
        int next_num = 0;

        for (int k = 0; k < seq_num; k++)
        {
            next_num = first + ( * );
        }
        return next_num;
    }

}

我不确定如何写产品。

1 个答案:

答案 0 :(得分:1)

要生成数字数字的乘积,请使用十进制数字的属性。换句话说,除以十并取余数(模10)。无需将其转换为字符串并获取单个字符并将其转换为整数。

public long digitProduct (long anInteger) throws Exception {
    if (anInteger <= 0) {
        throw new Exception ("digitProduct:  input integer " + anInteger +
            " is less than or equal to zero.");
    }
    long product = 1;
    do {
        product = product * (anInteger % 10);  // modulo 10 is last digit.
        anInteger = anInteger / 10;  // Shifts out last digit.
    } while (anInteger > 0);
    return product;
} // digitProduct (long)

使用longs因为产品可能会很快变大。考虑使用BigInteger。