// Online question from the sample final exam // I further refined my answer from original as I developed it // Beth Katz - April 2009 import java.util.Scanner; public class Final { final static int MaxItems = 100; public static void main(String[ ] args) { int[ ] inventory = new int[MaxItems]; Scanner input = new Scanner(System.in); int numItems = fillInventory(inventory, input); sell(inventory, numItems, input); } // fills inventory array and returns the number of possible items // for user to choose public static int fillInventory(int[ ] inventory, Scanner input) { int count = 0; int amount; System.out.println("Please enter the inventory amounts:"); amount = input.nextInt( ); // read before loop while (amount >= 0) { inventory[count] = amount; count++; amount = input.nextInt( ); // read at bottom of loop } System.out.println(count + " items read."); return count; } // sell items from inventory array public static void sell(int[ ] inventory, int items, Scanner input) { int current; System.out.println("Please enter item numbers:"); while (input.hasNextInt( )) { current = input.nextInt( ); if (current < 0 || current >= items) { System.out.println(current + " is not a valid items number." + " Should be from 0 to " + (items-1)); } else { reduceStock(inventory, items, current); } } } // reduce stock in inventory[itemNum] if it is available // reports unavailability or that it was sold and remaining stock public static void reduceStock(int[ ] inventory, int items, int itemNum) { if (inventory[itemNum] <= 0) { System.out.println("Item number " + itemNum + " is not in stock"); } else { inventory[itemNum]--; System.out.println("Item number " + itemNum + " sold, " + inventory[itemNum] + " remains"); } } }