开发者

Problem with output, Java

I need for my output to be the first 100 pentagonal numbers, ten per row , counting in succession. As it stands my output just repeats itself, i am sure this is a simple answer but i cant seem to come up with it. This was homework and already graded but i would like to figure it out for me to learn. Thanks in advance for any input and help.

package chapter_5;

/**
开发者_StackOverflow *
 * @author jason
 */
public class Five_One {


    public static void main(String[] args) {
        for (int k = 1; k < 11; k++) {
            for (int n = 1; n < 11; n++) {
                System.out.print(getPentagonalNumber(n)+ "\t");
            }
            System.out.println();

        }        
 }

    public static int getPentagonalNumber(int n) {
        return  n * (3 * n - 1) / 2;

  }

} 


you are repeatedly calling getPentagonalNumber() with numbers in range [1,10], instead of calling numbers in increasing range. can be solved by adding 10*k [and running k from 0 to 10 instead 1 to 11]

public static void main(String[] args) {
        for (int k =0; k < 10; k++) { //range is [0,10) instead [1,11)
            for (int n = 1; n < 11; n++) {
                System.out.print(getPentagonalNumber((10*k)+n)+ "\t"); //10*k + n instead of n
            }
            System.out.println();

        }        
}


It should be:

    System.out.print(getPentagonalNumber((k-1) * 10 + n) + "\t");

because if not, you are writing the first 10 pentagonal numbers, ten times.

In any case, I'd rather try to focus on creating a code that is as easy to read/maintain as possible, so I'd use only one loop:

    for (int i = 0; i < 100; i++) {
        System.out.print(getPentagonalNumber(i + 1) + "\t");
        if (i % 10 == 0) {
            System.out.println();
        }
    }  


If you need the first 100 pentagonal numbers, you only need one for-loop going from 1 to 100.

Hope this helps.


Your output contains

getPentagonalNumber(n)

where n is the column number. Thus each row is the same.

You'll have to incorporate the row number k also in you calculation:

getPentagonalNumber((k-1) * 10 + n)

i.e. from row to row your index is increased by 10.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜