Bradly Hedge Bradly Hedge - 1 month ago 9
Java Question

How to print each element of an array to a different line?

This is what I have now. I am trying to print each value to a different line (requirement no.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));
}


}

The output is:

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


However I need them on different lines.
I have tried various methods like:

}
System.out.println(nums);
}


But this just returns the character string:

[J@15db9742


I have tried other various methods, but this is the closest I've gotten, and I've looked up various methods to outputting each element to its own line, but since I'm new to coding I couldn't make sense of them or figure out how to get them to work with my code. Any help would be appreciated.
Thanks!

Answer

To print element on a new line just simply add another for-loop.

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

OR try this..

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