java - Print Fibonacci number -
my program supposed output fibonacci number based on user has entered (ex. if enter 7 program output 13). portion works. part having trouble when program checks makes sure number user entered positive , less or equal 70. it supposed ask user input again, instead outputs "fibonacci #-1 0" , stops. here's code:
import java.util.scanner; public class scalvert_fibonacci { public static void main ( string args[] ) { scanner input = new scanner ( system.in ); int sum = 0; int num; int f1 = 0, f2 = 0, f3 = 1; system.out.print("which fibonacci number like? "); num = input.nextint(); if (num == 0) return 0; else if (num == 1) return 1; while (num < 0 || num > 70) { system.out.print("which fibonacci number like? "); num = input.nextint(); } for(int = 1; <= num; i++) { f1 = f2; f2 = f3; f3 = f1 + f2; } system.out.printf("fibonacci #%d %d\n",num, f2); } }
using might solve problem
if(num<0 || num>70) { //ask number again } else { //calculate } or use if( 0 < num < 71 ) { //calculate } else { //ask valid number }
Comments
Post a Comment