Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2014
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. package iterator;
  2. import java.util.Iterator;
  3. public class Driver {
  4.  
  5. public static void main(String args[]) {
  6. Prison prison= new Prison(5);
  7. Iterator<PrisonCell> iter;
  8.  
  9. prison.addCell(new PrisonCell("A", 3));
  10. prison.addCell(new PrisonCell("B", 9));
  11. prison.addCell(new PrisonCell("C", 6));
  12.  
  13. iter= prison.iterator(); //I want to make the iterator() method in my Prison class
  14.  
  15. while (iter.hasNext())
  16. System.out.println(iter.next());
  17. }
  18. /**output here would be:
  19. Name: A, numPrisoners: 3
  20. Name: B, numPrisoners: 9
  21. Name: C, numPrisoners: 6
  22. **/
  23.  
  24. }
  25.  
  26.  
  27.  
  28. package iterator;
  29. public class PrisonCell { //how would I implement the Iterable<> iterface here?
  30.  
  31. private String name;
  32. private int numPrisoners;
  33.  
  34. public PrisonCell(String name, int numPrisoners) {
  35. this.name= name;
  36. this.numPrisoners= numPrisoners;
  37. }
  38.  
  39. public String toString() {
  40. return "Name: " + name + ", numPrisoners: " + numPrisoners;
  41. }
  42.  
  43. }
  44.  
  45.  
  46.  
  47. package iterator;
  48. public class Prison{
  49.  
  50. PrisonCell prisonCells[];
  51. int numPrisonCells;
  52.  
  53. public Prison(int size) {
  54. prisonCells= new PrisonCell[size];
  55. numPrisoners= 0;
  56. }
  57.  
  58. // just do nothing if the array is full
  59. public void addCell(PrisonCell newPrisonCell) {
  60. if (numPrisonCells < prisonCells.length)
  61. prisonCells[numPrisonCells++]= newPrisonCell;
  62. }
  63.  
  64. //how do I write iterator() method here??
  65. }
  66.  
  67.  
  68.  
  69. package iterator;
  70. public class Iterator<PrisonCell>//is it supposed to implement an interface here?
  71. //which fields here?
  72. public Iterator() //constructor here
  73. //I think boolean hasNext() and PrisonCell next() methods go here?
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement