user6816517 - 4 months ago 26

Java Question

I need help with my java-program. This program is supposed to ask for the highest value fibonacci can have, and print out the number of series up to that value, but it doesn't work. Any suggestions?

`import java.util.Scanner;`

public class Fibonacci {

public static void main (String[] args){

Scanner in = new Scanner(System.in);

System.out.println("The largest number fibonacci can be: ");

int number = in.nextInt();

if (number < 0){

System.out.println("Wrong! Max-value has to be at least 0.");

}

int i;

int f0 = 0;

int f1 = 1;

int fn;

int value=0;

for (i = 0; i<=value; i++){

fn = f0 + f1;

System.out.println("Fibonacci-number " + i + " = " + f0);

f0 = f1;

f1 = fn;

value = number - f0;

}

}

}

If i put in

`number = 12`

`fibonacci-number 0 = 0`

...

fibonnaci-number 12 = 144

Answer

Just change the loop to compare value of increment-er (i) to 'number ' variable

```
for (i = 0; i<=number; i++){
//.........
}
```

Also use double instead of int if you want to print higher number in the series correctly.

There is no use of the 'value' variable.

Also, the phrase 'the highest value fibonacci can have' is misleading.You have mentioned number denotes number of terms in the series in your example.

If you want 'number' to be the highest value in the series, use following approach,

```
do{
fn = f0 + f1;
System.out.println("Fibonnaci-tall " + i + " = " + f0);
f0 = f1;
f1 = fn;
i++;
}while(f0<=number);
```