Hello @Asmae!
Thanks for reaching out to us. There are two types of errors in your code.
-
Syntax errors
In this code, One closing bracket (}
) for the class is missing at the end and also you have added one extra opening bracket({
) after while(i<n);
.
-
Logical errors
The following code should be in the do while loop.
x = y;
y = z;
z = x +y;
You just need to concatenate the value of x in a string named fib at start of do while loop such as.
fib += String.valueOf(x)+",";
The following line is not needed at all.
fib += String.valueOf(z) + " ";
The final code should be like that:
class Fibonacci {
public static String test(int n) {
String fib = “”;
int x = 0;
int y = 1;
int z = x + y;
int i = 0;
do{
fib += String.valueOf(x)+",";
x = y;
y = z;
z = x +y;
i++;
}while (i < n);
return fib;
}
public static void main(String[] args) {
System.out.println(test(10));
}
}
Note: if you dry run your code, you will find out that in the first iteration of the ** do while** loop, the value of string fib will become ``` 0 1 1" then in each iteration you are concatenating the same values (0,1,1 ) in the string because you didn’t update values of variables in ** do while** loop.
After loop, you have updated values of variables (x,y,z) and then concatenated the value of z in string fib.
For example (if n=5) then in the first 5 iterations, your string will become “0 1 1 0 1 1 0 1 1 0 1 1 0 1 1” and after loop you have concatenated value of z (“2”).
I hope this will help. Thanks