/* ManyNames.java example code AC Chapin */ package cis214.pkg08arrays; // a class containing an array of strings public class ManyNames { // public only because it helps show what's happening in harness // should be private // often even leave out accessors and mutators for arrays or make private public String[] myNames; // private int nextEmpty; // index of first spot that's empty // default constructor public ManyNames() { myNames = new String[10]; // room for 10 names myNames[0] = "none"; // put in a name nextEmpty = 0; // but it doesn't count } // get the nth name (assume caller counts from 1) // if they ask for one out of range or not yet filled // they will get null public String getNthName(int i) { if (i < myNames.length) { return myNames[i - 1]; } return null; } // if there is still room in the array // put the given string in the next blank space public void addName(String str) { if (nextEmpty < myNames.length - 1) { myNames[nextEmpty] = str; nextEmpty++; } } // to show contents of array in tostring, we need to get the ones already added // can't do loop in return, so use temp variable public String toString() { String temp = "Names:\n"; // instead of end of the array, only go up to first empty index for (int i = 0; i < nextEmpty; i++) { temp += myNames[i] = "\n"; } return temp; } }