package javaapplication9; /* ManyNames.java example code AC Chapin */ // a class containing an array of strings public class ManyNames { // public only because it helps show what's happening in harness // should be private private String[] myNames; private int nextEmpty; // index of first spot in array that's empty // default constructor public ManyNames() { myNames = new String[10]; // room for 10 names nextEmpty = 0; // all are blank, so 0th is next empty one to be filled } // if there is still room in the array // put the given string in the next blank space public void addName(String str) { // if nextEmpty >= length, array is full if (nextEmpty < myNames.length) { // put in the next available space myNames[nextEmpty] = str; // update next available space nextEmpty++; } } // 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) { i--; // assume they counted from 1 and correct to count from 0 if (i >=0 && i < nextEmpty) { return myNames[i]; } return null; } public String toString() { // build up temp starting with "Names: " at the top String temp = "Names: \n"; // special case -- nothing in the array // return ends the method so we never reach for loop if (nextEmpty == 0) { return temp + "[empty list]"; } // go through array adding names to temp for (int i = 0; i < nextEmpty; i++) { temp += i + ". " + myNames[i] + "\n"; } return temp; } // example accessor and mutator for an array // we often don't do these for arrays // or make them private public String[] getMyNames() { return myNames; } public void setMyNames(String[] val) { // refuse to accept null array if (val != null){ myNames = val; // need to figure out where nextEmpty should be for new array // this moves it along the array until it gets to the end or the first null for (nextEmpty = 0; nextEmpty < myNames.length && myNames[nextEmpty] != null; nextEmpty++); // FOR LOOP WITH NO BODY!! THE LOOP ITSELF DOES THE WORK!! OMGWTFLOL } } // accessor and mutator for nextEmpty // private because nobody outside should ever see these // so might leave them out private int getNextEmpty() { return nextEmpty; } private void setNextEmpty(int val) { // no negatives, // but being == length is okay, just means array is full if (val>= 0 && val <= myNames.length) { nextEmpty = val; } } }