Question: How do you count the items in array? like the output would be: The grocery items are: Item [name=Banana, weight=5] Item [name=Apple, weight=4] Item [name=Orange,

How do you count the items in array?

like the output would be:

The grocery items are:

Item [name=Banana, weight=5]

Item [name=Apple, weight=4]

Item [name=Orange, weight=3]

Total Weight = 12

Total number of items in your list is: 3

CODE:

///Item.java

//Class: Item public class Item { //private fields private String name; private int weight; //Constructor public Item(String name, int weight) { this.name = name; this.weight = weight; }

//getter for name public String getName() { return name; }

//getter for weight public int getWeight() { return weight; }

@Override //method to represent an item public String toString() { return "Item [name=" + name + ", weight=" + weight + "]"; } }

/////Main.java

//Main class containing main method public class Main { public static void main(String[] args) { //Item array names groceryItem is initialized with 3 Item objects Item groceryItem[] = { new Item("Banana",5), new Item("Apple",4), new Item("Orange",3) }; //Initialize int variable totalWeight to 0 int totalWeight = 0; System.out.println("The grocery items are:"); //Through enhanced for loop iterate through each Item in groceryItem array for(Item item: groceryItem) { System.out.println(item.toString());//print the Item totalWeight = totalWeight + item.getWeight();//add up current Item;s weight to totalWeight } System.out.println("Total Weight = "+totalWeight);//finally print total weight }

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!