Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Reading from file into arrays
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
slider203




PostPosted: Mon Apr 12, 2010 10:27 pm   Post subject: Reading from file into arrays

Hello I need to create a program that reads in 12 numbers from a file and stores them in an array. The program will also has to calculate the average of all numbers and only output numbers that are lower than the average.

Here is my code so far:
code:

import java.io.*;
class arrayfileread
{
  public static void main (String args [])
  throws java.io.IOException
  {
    FileReader fr = new FileReader ("income.txt");
    BufferedReader bfr = new BufferedReader (fr);
   
    final int MAX = 12;
    String input = "";
    double[] incomes = new double[MAX];
    double average = 0;
   
    for (int count = 0; count < MAX; count++)
    {
    input = bfr.readLine();
    incomes[count] = Double.parseDouble (input);
    average = incomes[count] + average;
    System.out.println (incomes[count]);
    }
    average = average / MAX;
    System.out.println (incomes[MAX]);
    fr.close();
  }
}


When I run the program It outputs 11 numbers instead of 12 and puts this error message:
java.lang.ArrayIndexOutOfBoundsException: 11
at arrayPrac1.main(arrayPrac1.java:35)

Thannk you in advance
Sponsor
Sponsor
Sponsor
sponsor
Zren




PostPosted: Mon Apr 12, 2010 10:57 pm   Post subject: RE:Reading from file into arrays

System.out.println (incomes[MAX]);
final int MAX = 12;

Array incomes start at 0 and end at _?

As far as I can see, it should be printing all 12 though...
slider203




PostPosted: Tue Apr 13, 2010 6:53 am   Post subject: RE:Reading from file into arrays

Ive tried changing MAX to 11 still wont work
Zren




PostPosted: Tue Apr 13, 2010 8:55 am   Post subject: RE:Reading from file into arrays

Dude.

Array's in java start from 0. So if I were to declare int[] array = int[5] would have the following indexes: "0, 1, 2, 3, 4" For a total of 5 different indexes, but the last index is 4. So System.out.println(array[4]) would print the last number.

You changed the upper value of the array so it's still going out of bounds... It's almost like you should look at one below MAX...

Though it looks like your just using those println's for debugging. Why not just delete it and go to the next part of the code (checking the array).
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 4 Posts ]
Jump to:   


Style:  
Search: