如何将数组的每个元素打印到不同的行?

时间:2016-10-19 00:50:00

标签: java arrays fibonacci

这就是我现在所拥有的。我试图将每个值打印到不同的行(要求号5)。

public class Function {

public static BufferedReader lifeIsBuff = new BufferedReader(new InputStreamReader(System.in));

public static void run() throws IOException {

    FibonacciCalculator();

}

public static void FibonacciCalculator() throws IOException {

    //1: Prompt the user for a positive number.
    //2: Initialize an array to that size.
    //3: Populate indices 0 and 1 with the value of 1.
    //4: Using a for loop, populate the remaining spaces in the array with the correct Fibonacci value.
    //5: Print each value to the console in their own lines.
    //6: This app runs once and closes.

    System.out.println("Please enter a positive number: ");
    String input = lifeIsBuff.readLine();
    int arraySize = Integer.parseInt(input);

    long[] nums = new long[arraySize];
    nums [0] = 1;
    nums [1] = 1;

    for (int i = 2; i < nums.length; i++) {
        nums [i] = nums [i - 1] + nums [i - 2];
    }   
    System.out.println(Arrays.toString(nums));
}

}

输出结果为:

    [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]

但是我需要不同的线路。 我尝试了各种方法,如:

    }   
    System.out.println(nums);
}

但这只返回字符串:

    [J@15db9742

我尝试了其他各种方法,但这是我得到的最接近的方法,我已经查找了各种方法将每个元素输出到自己的行,但由于我是新手编码,我无法制作他们的感觉或弄清楚如何让他们使用我的代码。任何帮助,将不胜感激。 谢谢!

1 个答案:

答案 0 :(得分:0)

要在新行上打印元素,只需添加另一个for循环。

for (int i = 0; i < nums.length; i++) {
    System.out.println(nums[i]);
}   

OR 试试这个..

for (int i = 2; i < nums.length; i++) {
    nums [i] = nums [i - 1] + nums [i - 2];
     System.out.println(nums[i]);
}