Created
November 9, 2015 15:20
-
-
Save OOPUniversity/0ac824ec6d21558743ab to your computer and use it in GitHub Desktop.
Demonstration for 'Arrays of Golden Sun' blog post
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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