TurkuBasicOOPinJava / Week 5: Class hierarchies /16. Own Exceptions 3: Catching Exceptions
KaiquanMah's picture
catch (CustomException e)
dcba1b0 verified
raw
history blame
2.76 kB
Write a method
public static void addToGroup(SuperGroup group, ArrayList<SuperAnimal> animals)
which receives a 'super group' and 'a list of super animals' as arguments.
Method tries to add the members to group one at a time.
For each animal, the method outputs if the adding was successful or not (see the example below).
After iterating through all animals, the group is output using the 'outputGroup method' in class SuperGroup.
Example of calling the method:
public static void main(String[] args) {
//LIST OF ANIMALS
ArrayList<SuperAnimal> al = new ArrayList<>();
al.add(new SuperAnimal("pig", "Fifer", "Super musician"));
al.add(new SuperAnimal("cat", "Crazy Kat", "Super strength"));
al.add(new SuperAnimal("dog", "Super Snoops", "Super barking"));
//GROUP
SuperGroup group = new Supergroup(The Barkvengers");
// FOR SPECIFIED GROUP, ADD LIST OF ANIMALS
addToGroup(group, al);
}
Program outputs:
Success: Fifer (pig), super strength: Supermusisointi
Success: Crazy Kat (cat), super strength: Super strength
Fail: Super Snoops(dog), super strength: Super barking
The Barkvengers
Fifer (pig), super strength: Super musician
Crazy Kat (cat), super strength: super strength
======================================
import java.util.Random;
import java.util.ArrayList;
import java.util.Collections;
public class Test{
public static void main(String[] args){
final Random r = new Random();
ArrayList<SuperAnimal> al = new ArrayList<>();
al.add(new SuperAnimal("pig", "Mr. Piggy", "Superbreath"));
al.add(new SuperAnimal("cow", "Captain Moo", "Supermilk"));
al.add(new SuperAnimal("cat", "Felixx", "Super vision"));
al.add(new SuperAnimal("cat", "Car-Field", "Supercar"));
Collections.shuffle(al, r);
SuperGroup group = new SuperGroup("Ryhmä Äks");
addToGroup(group, al);
}
//ADD
public static void addToGroup(SuperGroup group, ArrayList<SuperAnimal> animals) {
for (SuperAnimal animal : animals) {
try {
group.addMember(animal);
System.out.println("Success: " + animal);
}
catch (SuperException e) {
System.out.println("Fail: " + animal);
}
}
group.outputGroup();
}
}
Success: Felixx (cat), superStrength: Super vision
Success: Car-Field (cat), superStrength: Supercar
Success: Captain Moo (cow), superStrength: Supermilk
Success: Mr. Piggy (pig), superStrength: Superbreath
Ryhmä Äks
Felixx (cat), superStrength: Super vision
Car-Field (cat), superStrength: Supercar
Captain Moo (cow), superStrength: Supermilk
Mr. Piggy (pig), superStrength: Superbreath