Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Beginning C# 2005 Databases

Authors: Karli Watson

1st Edition

0470044063, 978-0470044063

More Books

Students also viewed these Databases questions