Question

In: Computer Science

The following code is included for the java programming problem: public class Bunny {        private...

The following code is included for the java programming problem:

public class Bunny {

       private int bunnyNum;

       public Bunny(int i) {

              bunnyNum = i;

       }

       public void hop() {

              System.out.println("Bunny " + bunnyNum + " hops");

       }

}

  • Create an ArrayList <????> with Bunny as the generic type.
  • Use an index for-loop to build (use .add(….) ) the Bunny ArrayList. From the output below, you need to have 5.
  • Use an index for-loop to call each of the Bunny hop( ). You need to use .get(i) to call the hop( ) of each Bunny.
  • Write an enhanced for-loop to display the Bunny hops. You don’t need to use the .get(i) call.
  • Create an Iterator<Bunny> reference variable, and use it to iterate through the Bunny ArrayList with the .hasNext() and .next() to get to the hop().

Display the following output:

+++++++++++ hop in for-loop

Bunny 0 hops

Bunny 1 hops

Bunny 2 hops

Bunny 3 hops

Bunny 4 hops

----------- hop in Enhanced-loop

Bunny 0 hops

Bunny 1 hops

Bunny 2 hops

Bunny 3 hops

Bunny 4 hops

*********** hop in Iterator style

Bunny 0 hops

Bunny 1 hops

Bunny 2 hops

Bunny 3 hops

Bunny 4 hops

Solutions

Expert Solution

I have implemented the program to iterate the ArrayList using for,enhanced-for and iterator  per the given description.

Please find the following Code Screenshot, Output, and Code.

ANY CLARIFICATIONS REQUIRED LEAVE A COMMENT

1.CODE SCREENSHOT :

2.OUTPUT :

3.CODE :

Main.java

import java.util.*;
public class Main{
        public static void main(String args[]){
                //create a array list to store "Bunny" Class object
                ArrayList<Bunny> a=new ArrayList<Bunny>();
                int i;
                //use for loop to store 5 obejcts 
                for(i=0;i<5;i++)
                        a.add(new Bunny(i));
                //use for loop to iterate
                System.out.println("+++++++++++ hop in for-loop");
                for(i=0;i<5;i++)
                        a.get(i).hop();
                //use enhanced for loop to iterate
                System.out.println("----------- hop in Enhanced-loop");
                for (Bunny b:a)
                        b.hop();
                //create a iterator
                 Iterator<Bunny> itr=a.iterator();
                 System.out.println("*********** hop in Iterator style");
                 //iterate using iterator
                while(itr.hasNext())
                        itr.next().hop();
        }
}

Bunny.java

public class Bunny {

       private int bunnyNum;

       public Bunny(int i) {

              bunnyNum = i;

       }

       public void hop() {

              System.out.println("Bunny " + bunnyNum + " hops");

       }

}

Related Solutions

java code ============ public class BankAccount { private String accountID; private double balance; /** Constructs a...
java code ============ public class BankAccount { private String accountID; private double balance; /** Constructs a bank account with a zero balance @param accountID - ID of the Account */ public BankAccount(String accountID) { balance = 0; this.accountID = accountID; } /** Constructs a bank account with a given balance @param initialBalance the initial balance @param accountID - ID of the Account */ public BankAccount(double initialBalance, String accountID) { this.accountID = accountID; balance = initialBalance; } /** * Returns the...
COMPLETE JAVA CODE public class Point2 { private double x; private double y;    /** *...
COMPLETE JAVA CODE public class Point2 { private double x; private double y;    /** * Create a point with coordinates <code>(0, 0)</code>. */ public Point2() { complete JAVA code this.set(0.0, 0.0); COMPLETE CODE }    /** * Create a point with coordinates <code>(newX, newY)</code>. * * @param newX the x-coordinate of the point * @param newY the y-coordinate of the point */ public Point2(double newX, double newY) { complete Java code this.set(newX, newY); }    /** * Create a...
Fill in the following blanks for java code::: import java.util.NoSuchElementException; public class CircularQueue<E> {    private...
Fill in the following blanks for java code::: import java.util.NoSuchElementException; public class CircularQueue<E> {    private E[] queue;    private int front = 0, rear = 0;    private static final int DEFAULT_CAPACITY = 5;       public CircularQueue(int capacity)    {    queue = (E[]) new Object[capacity + 1];    }       public CircularQueue()    {        this(DEFAULT_CAPACITY); }       //Add a method that will determine if the queue is empty. Recall that the queue is...
Please add comments to this code! JAVA Code: import java.text.NumberFormat; public class Item {    private...
Please add comments to this code! JAVA Code: import java.text.NumberFormat; public class Item {    private String name;    private double price;    private int bulkQuantity;    private double bulkPrice;    /***    *    * @param name    * @param price    * @param bulkQuantity    * @param bulkPrice    */    public Item(String name, double price, int bulkQuantity, double bulkPrice) {        this.name = name;        this.price = price;        this.bulkQuantity = bulkQuantity;        this.bulkPrice = bulkPrice;   ...
Please add comments to this code! JAVA code: import java.util.ArrayList; public class ShoppingCart { private final...
Please add comments to this code! JAVA code: import java.util.ArrayList; public class ShoppingCart { private final ArrayList<ItemOrder> itemOrder;    private double total = 0;    private double discount = 0;    ShoppingCart() {        itemOrder = new ArrayList<>();        total = 0;    }    public void setDiscount(boolean selected) {        if (selected) {            discount = total * .1;        }    }    public double getTotal() {        total = 0;        itemOrder.forEach((order) -> {            total +=...
Programming Exercise Implement the following class design: class Tune { private:    string title; public:   ...
Programming Exercise Implement the following class design: class Tune { private:    string title; public:    Tune();    Tune( const string &n );      const string & get_title() const; }; class Music_collection { private: int number; // the number of tunes actually in the collection int max; // the number of tunes the collection will ever be able to hold Tune *collection; // a dynamic array of Tunes: "Music_collection has-many Tunes" public: // default value of max is a conservative...
java programing Q: Given the following class: public class Student { private String firstName; private String...
java programing Q: Given the following class: public class Student { private String firstName; private String lastName; private int age; private University university; public Student(String firstName, String lastName, int age, University university) { this.firstName = fisrtName; this.lastName = lastName; this.age = age; this.university = university; } public String getFirstName(){ return firstName; } public String getLastName(){ return lastName; } public int getAge(){ return age; } public University getUniversity(){ return university; } public String toString() { return "\nFirst name:" + firstName +...
Java programming. Write a public Java class called DecimalTimer with public method displayTimer, that prints a...
Java programming. Write a public Java class called DecimalTimer with public method displayTimer, that prints a counter and then increments the number of seconds. The counter will start at 00:00 and each time the number of seconds reaches 60, minutes will be incremented. You will not need to implement hours or a sleep function, but if minutes or seconds is less than 10, make sure a leading zero is put to the left of the number. For example, 60 seconds:...
I needv pseudocode and a flowchart for the following java code public class AcmePay { public...
I needv pseudocode and a flowchart for the following java code public class AcmePay { public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(System.in); int hours, shift, retirement = 0; do { System.out.print("Enter the number of hours worked (>0): "); hours = scanner.nextInt(); } while (hours <= 0); do { System.out.print("Enter shift [1 2 or 3]: "); shift = scanner.nextInt(); } while (shift < 1 || shift > 3); if (shift == 2 || shift ==...
UML Diagram for this java code //java code import java.util.*; class Message { private String sentence;...
UML Diagram for this java code //java code import java.util.*; class Message { private String sentence; Message() { sentence=""; } Message(String text) { setSentence(text); } void setSentence(String text) { sentence=text; } String getSentence() { return sentence; } int getVowels() { int count=0; for(int i=0;i<sentence.length();i++) { char ch=sentence.charAt(i); if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u' || ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U') { count=count+1; } } return count; } int getConsonants() { int count=0; for(int i=0;i<sentence.length();i++)...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT