- Forward


Using Arrays of "Structs"
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • Recall:
    • Conformal arrays make it possible to work with "records" consisting of multiple "fields"
  • An Inconvenience:
    • All of the arrays must be passed to methods that need them
An Alternative Pattern
Back SMYC Forward
  • Use an Array of "struct" Objects:
    • Create a class that holds the values "side-by-side" (which needn't have methods and might even have public attributes for convenience)
    • Create an array of these objects
  • About the Name:
    • Some languages (e.g., C) have this capability
    • A struct is a collection of heterogeneous elements (unlike an array which is a collection of homogeneous values)
An Example
Back SMYC Forward
public class Sales { public double amount; public String code; }
double mean, total; Sales[] sales; int month; sales = new Sales[12]; month = 0; while (month < 12) { JMUConsole.printf("Enter the 3-letter code for %d: ", month); sales[month].code = JMUConsole.readLine(); System.out.printf("Enter the sales for %s: ", code[month]); sales[month].amount = JMUConsole.readDouble(); month++; }
There's Always More to Learn
Back -