Results 1 to 5 of 5

Thread: Java Question     submit to reddit submit to twitter

  1. #1
    Pens win! Pens Win!!! PENS WIN!!!!!
    Join Date
    Jul 2008
    Posts
    8,633
    BG Level
    8

    Java Question

    Hey there. I'm having a problem with a simple concept on arrays. What the program that I am about to post does is that it simple takes user input of doubles and plugs them into the array. As this is being done, an average of the current numbers of the array is the output. But once the array size reaches the "windowSize" (which is 5 by default, unless changed via arguments), the method gets the average of the last n (windowSize) numbers inputed into the array. I am supposed to overwrite the old elements (once the array length reaches over the windowSize) as more numbers are input. My code so far:

    Code:
    // fill in your information in the line below, and comment it out in order to compile
    //Name: XXX   Student ID: XXX
    
    import javax.swing.JOptionPane;
    
    public class Assignment1 {
      // define data members here
      private double[] price;
      private int counter;
      private int elements;
      private int n;
      
      public Assignment1 ( int in ){
        // fill in code here
        n  = in;
        price = new double[n];
        elements = 0;
        counter=0;
      }
      
      public void addNumber (double value){
        // fill in code here
        price[elements] = value;
        elements++; counter++;
      }
      
      public double getAverage(){
        // fill in code here
        double answer= 0;
        for(int i =0; i <= elements; i++)
        {
            answer = answer + price[i];
        }
        double average = answer / elements;
        return average;
      }
      
      public int totalNumbers(){
        // fill in code here
        return counter;
      }
      
      
      public static void main(String[] args) {
        
        // default window size is 5
        int windowSize = 5;
        // you can also provide the window size from command line parameter
        if (args.length > 0)
          windowSize = Integer.parseInt(args[0].trim());
        System.out.println( "Running Average with window size " + windowSize );
        Assignment1 rAverage = new Assignment1( windowSize );
        
        double price = 0.0;
        // keep entering stock values
        // until you enter a zero, a negative number, or a non-number
        do {
          String numberString = JOptionPane.showInputDialog ("Please enter a stock price!");
          try{
            price = Float.parseFloat(numberString.trim()); 
          }
          catch(java.lang.Exception exception){
            price = 0;
          }
          if (price > 0){ 
            rAverage.addNumber (price);
            System.out.println( "Smoothed stock price is " +  
                               rAverage.getAverage() + "." ); 
          } 
        } while (price > 0);
        
        System.out.println( "You entered a total of " + 
                           rAverage.totalNumbers() +
                           " stock prices and the average of the last " + 
                           windowSize + " was " + rAverage.getAverage() );
        
      }
    }
    The assignment asks for both the main method to be in the same file. As you can see I am just getting the average of all the elements as more are put in the array. Although, I get a OutofBounds exception once i input 5 numbers. If I hardcode some larger number into the price array, then obviously I don't get the exception until I reach that amount of numbers.

    Any help would be appreciated. Thanks a bunch!

  2. #2
    The Wang
    Join Date
    Jun 2006
    Posts
    1,343
    BG Level
    6
    FFXIV Character
    Furt Wangler
    FFXIV Server
    Coeurl
    FFXI Server
    Sylph

    This may be totally incorrect advice as I only know python so take it with a grain of salt, but is it possible to set the windowsize to the lenth of the array? I know in python you could do something like len(string), or if that's not possible, to implement a counter in a for loop that iterates over the list and in turn counts the size of the list.

  3. #3
    Relic Shield
    Join Date
    Jul 2008
    Posts
    1,951
    BG Level
    6
    FFXIV Character
    Audrey Weaver
    FFXIV Server
    Behemoth
    FFXI Server
    Asura

    Sounds like you're trying to implement a queue, with a maximum capacity of windowSize.

    You're not checking if the array index is valid in addNumber in the cases in which it's not supposed to grow. Indexing memory outside array bounds is causing the exception. You're also not moving the numbers back when the queue is full and a new item is added.

  4. #4
    Bagel
    Join Date
    Jan 2006
    Posts
    1,428
    BG Level
    6

    OutOfBounds is probably because you are attempting to add more elements to the price array than it can hold.

    If you're supposed to overwrite the older numbers, just change the element index variable back to 0 once it is greater than or equal to the window size.

    You don't need to store all the numbers, only the ones that matter. You'll also have to alter your getAverage function to be based on the windowSize, not the element variable


    and just as an additional hint, only need to change two functions, and only maybe 5 lines to get this working right. Pretty simple change.

  5. #5
    CoP Dynamis
    Join Date
    Sep 2007
    Posts
    271
    BG Level
    4

    I didn't read through all your code beforehand so if you are doing this already, forgive me.

    If you are only trying to keep up with an array of windowSize, make the array that size to begin with. Keep an integer count of how many total items have been added so far. If you are to replace the oldest entry into the array once you reach the limit, use modulus to figure out which place in the array you are at to replace. (The operator for mod is % in Java)

    array[totalEntries % windowSize] = inputtedNumber

Similar Threads

  1. Java Question
    By Senoska in forum General Discussion
    Replies: 4
    Last Post: 2010-04-26, 21:43