Reputation: 487
public static String fibonacci(int a, int b){
int max = 10;
String returnValue;
int[] result = new int[max];
result[0] = a;
result[1] = b;
for (int i1 = 2; i1 < max; i1++) {
result[i1] = result[i1 - 1] + result[i1 - 2];
}
for (int i3 = 0; i3 < max; i3++) {
//Here you can do something with all the values in the array one by one
//Maybe make something like this?:
int TheINTthatHasToBeAdded = result[i3];
//The line where TheINTthatHasToBeAdded gets added to the String returnValue
}
return returnValue;
}
-
The result array has items that are INTEGERS, returnValue is a string.
My question is; how do I add the items that are in the result array, to the returnValue array?
Upvotes: 1
Views: 82
Reputation: 85779
To convert an array into a String
you can use java.util.Arrays.toString
:
returnValue = java.util.Arrays.toString(result);
Still, returning a String
representation of the calculated array is not a good design. It would be better to return the int[]
and let the client to convert this into a String
or another way to consume it or display it to the user.
This is how the method may look:
//changed the return type from String to int[]
public static int[] fibonacci(int a, int b) {
int max = 10;
int[] result = new int[max];
result[0] = a;
result[1] = b;
for (int i1 = 2; i1 < max; i1++) {
result[i1] = result[i1 - 1] + result[i1 - 2];
}
return result;
}
//in client method, like main
public static void main(String[] args) {
//store the result of fibonacci method in a variable
int[] fibonacciResult = fibonacci(0, 1);
//print the contents of the variable using Arrays#toString
System.out.println("Fibonacci result:" + Arrays.toString(fibonacciResult));
}
Or even use another way to consume the results. Here's another example:
public static void main(String[] args) {
//store the result of fibonacci method in a variable
int[] fibonacciResult = fibonacci(0, 1);
//print the contents of the variable using Arrays#toString
StringBuilder sb = new StringBuilder();
for (int i = 0; i < fibonacciResult.length; i++) {
sb.append(fibonacciResult[i])
.append(' ');
}
System.out.println("Fibonacci result:" + sb.toString());
}
Upvotes: 1
Reputation: 187
I assume you are trying to return a String containing all the fibonaci numbers you found? If you are, change the following:
StringBuilder returnValue = new new StringBuilder()
Add the following to your 2nd loop
returnValue.append(result[i3]).append(",");
Change the return value to:
return returnValue.toString();
This should solve it (With an extra ',' in the end)
Upvotes: 1