Instantly share code, notes, and snippets.

Embed
What would you like to do?
Demonstration for 'Arrays of Golden Sun' blog post
/*
* Copyright (c) 2014.
*/
package main.java.com.oopuniversity.basics.variables;
/**
* Created by OOPUniversity on 11/15/2014.
*/
public class Arrays {
int [] testResults = new int [ 20 ];
public static void main(String [] args) {
hardCodedTestScoresAverage();
randomTestScoresAverage();
}
static void hardCodedTestScoresAverage() {
int [] testScores = { 100, 95, 22, 84 };
System.out.println("Average is " + calculateAverage2(testScores));
}
static int getNumberOfScores() {
return 20;
}
static int getScore(int index) {
//We'll ignore the index for now
return (int)(Math.random()*100.0+1.0);
}
static void randomTestScoresAverage() {
int [] testScores = new int[ getNumberOfScores() ];
for ( int i = 0; i < getNumberOfScores(); i++ ) {
testScores[i] = getScore(i);
System.out.println("Score " + i + " is " + testScores[i]);
}
System.out.println("Average is " + calculateAverage2(testScores));
}
static float calculateAverage1( int [] valuesToAverage ) {
float total = 0;
for (int i = 0; i < 20; i ++ ) {
total = total + valuesToAverage[i];
}
return total / 20f;
}
static float calculateAverage2( int [] valuesToAverage ) {
float total = 0;
float valueCount = valuesToAverage.length;
for (int i = 0; i < valueCount; i++ ) {
total = total + valuesToAverage[i];
}
return total/valueCount;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment