Working with Fixed-Sized Arrays - Java Language Basics

Java examples for Language Basics:Array

Description

Working with Fixed-Sized Arrays

Demo Code

public class Main {

  private int[] myValues;

  public void setGrades(int[] grades) {
    this.myValues = grades;
  }//  www  .  j  a v a2s . co  m

  // Return cloned grades so the caller cannot modify our internal grades
  public int[] getGrades() {
    return myValues != null ? myValues.clone() : null;
  }

  public int meanGrade() {
    int mean = 0;
    if (myValues != null && myValues.length > 0) {
      int sum = 0;
      for (int i = 0; i < myValues.length; i++) {
        sum += myValues[i];
      }
      mean = sum / myValues.length;
    }
    return mean;
  }

  public int minGrade() {
    int min = 0;
    for (int index = 0; index < myValues.length; index++) {
      if (myValues[index] < min) {
        min = myValues[index];
      }
    }
    return min;
  }

  public int maxGrade() {
    int max = 0;
    for (int index = 0; index < myValues.length; index++) {
      if (myValues[index] > max) {
        max = myValues[index];
      }
    }
    return max;
  }

  static int[] initGrades() {
    int[] grades = { 57, 88, 67, 95, 99, 74, 81 };
    return grades;
  }

  public static void main(String... args) {

    Main ga = new Main();
    ga.setGrades(initGrades());
    System.out.println("Mean of all grades is " + ga.meanGrade());
    System.out.println("Min grade is " + ga.minGrade());
    System.out.println("Max grade is " + ga.maxGrade());

  }
}

Result


Related Tutorials