TurkuBasicOOPinJava / Week 4: Writing classes /13B. Calculate products together
KaiquanMah's picture
ClassName combined = new ClassName(param1, param2)
05fe4a9 verified
The program defines the class Product.
Write the method
public static Product calculate(Product product1, Product product2)
which takes two products as parameters.
The method creates and returns a new product in which the names of the products received as parameters
are combined with the 'and' word
and the quantities are added together.
Example of calling the method:
public static void main(String[] args) {
Product carrot = new Product("Carrot", 5);
Product potato = new Product("Potato", 7);
Product combined = calculate(carrot, potato);
System.out.println(combined.getName());
System.out.println(combined.getAmount());
}
Program outputs:
Carrot and Potato
12
============================
import java.util.Random;
public class Test{
public static void main(String[] args){
final Random r = new Random();
String[] products = {"Blueberry", "Strawberry", "Raspberry", "Grape",
"Lingonberry", "Cranberry", "Currant"};
for (int test=0; test<3; test++) {
String t1 = products[r.nextInt(products.length)];
String t2 = t1;
while (t1.equals(t2)) {
t2 = products[r.nextInt(products.length)];
}
Product product1 = new Product(t1, r.nextInt(20) + 1);
Product product2 = new Product(t2, r.nextInt(20) + 1);
System.out.println("Product 1: " + product1);
System.out.println("Product 2: " + product2);
Product product3 = calculate(product1, product2);
System.out.println("Names of the berries: " + product3.getName());
System.out.println("Combined quantity: " + product3.getAmount());
System.out.println("");
}
}
//ADD HERE
// inside 'Test' class, outside 'main' method
public static Product calculate(Product product1, Product product2) {
Product combined = new Product(product1.getName() + " and " + product2.getName(),
product1.getAmount() + product2.getAmount());
return combined;
}
}
class Product {
private String name;
private int amount;
public Product(String name, int amount) {
this.name = name;
this.amount = amount;
}
public String getName() {
return name;
}
public int getAmount() {
return amount;
}
@Override
public String toString() {
return "Product (name=" + name + ", amount=" + amount + ")";
}
}
Product 1: Product (name=Raspberry, amount=7)
Product 2: Product (name=Grape, amount=19)
Names of the berries: Raspberry and Grape
Combined quantity: 26
Product 1: Product (name=Blueberry, amount=20)
Product 2: Product (name=Grape, amount=5)
Names of the berries: Blueberry and Grape
Combined quantity: 25
Product 1: Product (name=Blueberry, amount=20)
Product 2: Product (name=Strawberry, amount=12)
Names of the berries: Blueberry and Strawberry
Combined quantity: 32