0

The program should print out the indexes in the array based on user input less than 25...so if the user enters in 7 the seven first elements of the array should be displayed....Not sure why I am getting a bounds error. I also having trouble wrapping my head around how the For Loop works.

import java.util.Scanner; public class FibbonacciSequencce {

public static void main(String[] args) {

    Scanner input = new Scanner (System.in);

    int[] anarray =  {0, 1, 1, 2, 3, 5, 8, 13, 21, 34,55,89,144,233,377,610,987,1597,2584,
            4181,6765,10946,17711,28657,46368 };

    System.out.println("Please enter a number, less than 25,: ");
    int number =  input.nextInt();
    if (number< 25){    
     for (int element=0; element<= number; element++){

        number = number +element;
        System.out.println(anarray[number]);
    }


    }
    else {
    System.out.println(" Enter a number less that 25");
    }
 }      

}
  • `element` is a confusing name, when it seems to be an index. And you are accessing the array by the value of `number`, which is a cumulative sum of `number + element`... Basically your code isn't doing what you described... And what if the array isn't sorted? Do you want to only look at the first 7 elements, or should you continue to look at all the elements and print those less than 25? – OneCricketeer Aug 28 '16 at 18:00
  • It should print out the number of array entries based on user input...So if I put in 5 it should print out the first five. – Rick Rosario Aug 28 '16 at 18:09
  • Okay, then how would you print the numbers 0 through 5? If you can answer that, you should be able to access the first 5 elements of any list – OneCricketeer Aug 28 '16 at 18:10
  • Sorry ...I really don't know how. I cant understand how the for loop works using input. – Rick Rosario Aug 28 '16 at 18:20
  • Just forget the input for a second... Do you understand the basics of the for loop? How would you print the numbers 0 though 5? 5 can be any number, so 0 though `n`? Start with that. Worry about the array and value checking and input later after you understand the basics. For loops always act and look the same, it's what happens inside that seems to be confusing you – OneCricketeer Aug 28 '16 at 18:24
  • for ( int x=0; x < anarray[5]; x++){ System.out.println(anarray[x]); } Seemed to work – Rick Rosario Aug 28 '16 at 18:29
  • Why are you using `anarray[5];`? If you used `anarray[9];` would you expect the first 9 elements be printed? – OneCricketeer Aug 28 '16 at 18:36
  • I'm using it to set the parameter to print the array elements ..I guess I am misunderstanding the book I am reading. – Rick Rosario Aug 28 '16 at 18:42
  • Probably, but that didn't answer my question. `anarray[9]` should throw an error. With regards to the 25 number, try replacing that with `anarray.length` – OneCricketeer Aug 28 '16 at 18:45

0 Answers0