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:
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.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() ); } }
Any help would be appreciated. Thanks a bunch!
XI Wiki

