Hello everyone! So I have to do this project for computer science class. We have to make a class that generates 50 odd numbers in order starting at 1 and stores them in an array of 50 int elements. Then we have to arrange the numbers we get so that there are only five in each row. Don't worry about the second part I only need help on the first! The code compiles fine but it always throws an arrayindexoutofboundsexception at the underlined line down there. Can anyone help me?

 * Write a description of class arrays here.
 * @author 
 * @version 1/31/2011
public class arrays
  public static void main (String [] args)
       int k, i;
       int [ ] odds = new int [50];
      for (i = 0; i <= odds.length; i++)
            for (k = 1; k <= 99; k+=2 )
           [B][U]odds[i] = k;[/U][/B]

don't use

for (i = 0; i <= odds.length; i++)


for (i = 0; i < odds.length; i++)

The array subscript for the last element is one less than array.length

Thanks for that but one more question. Whenever I compile this I only get 99's. So all of my array elements are filled with the number 99 but I don't know why. I need them to be filled with the first 50 odd numbers starting at 1.

that is because you are filling the same element over and over again ...
you are using

for (k = 1; k < 99; k+=2 ){
     odds[i] = k;

you are filling odds with k, while (k <= 99) but you don't change the value of i.
the same values are entered in each element of the array, and the value of k when it's entered in the element for the last time,happens to be '99' :)

ok thanks now it's working. Last question I promise! I have no idea how to make the array so it only has 5 numbers per row. Our teacher gave us this project on the first day we learned about arrays :/

I mean that it will display 5 numbers per row. Like row 1 has the first 5 odd numbers then row 2 has the next 5 etc. So there will be 10 rows with 5 numbers per row because I have 50 elements.

You may use a modulo operator that prints "\n" every time 5 characters are displayed.

//your code , use j for array subscript. a[j]

Or you may use a 2D array , which is quite elementary.

Edited 5 Years Ago by adarshcu: n/a

This question has already been answered. Start a new discussion instead.