Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.io.*;
- class TooManyWheelsException extends RuntimeException {
- }
- class Vehicle {
- private String name;
- private ArrayList<Wheel> wheels = new ArrayList<>();
- protected int needsWheels = 0;
- public Vehicle(String name){
- setName(name);
- }
- public void setName(String name){
- this.name = name;
- }
- public String getName(){
- return name;
- }
- public void addWheel(Wheel wheel){
- if (!hasAllWheels())
- wheels.add(wheel);
- else
- throw new TooManyWheelsException();
- }
- public boolean hasAllWheels(){
- return (wheels.size() == needsWheels);
- }
- public int getCurWheels(){
- return wheels.size();
- }
- public String toString(){
- return "Vehicle " + name + " " + needsWheels;
- }
- }
- class Car extends Vehicle {
- public Car(){
- super("Car");
- this.needsWheels = 4;
- }
- public String toString(){
- return "Car " + needsWheels;
- }
- }
- class Bicycle extends Vehicle {
- public Bicycle(){
- super("Bicycle");
- this.needsWheels = 2;
- }
- public String toString(){
- return "Bicycle " + needsWheels;
- }
- }
- class Wheel {
- public int diameter;
- }
- public class Sandbox {
- public static void main(String args[]) {
- try {
- ArrayList<Vehicle> vehicles = new ArrayList<>();
- for(int i = 0; i < 12; ++i){
- if (Math.random() < 0.3){
- vehicles.add(new Car());
- } else if (Math.random() < 0.6){
- vehicles.add(new Bicycle());
- } else {
- vehicles.add(new Vehicle("unknown"));
- }
- Vehicle v = vehicles.get(i);
- //while(!v.hasAllWheels())
- while(true)
- {
- try {
- System.out.println(v + " currently has " + v.getCurWheels() + " wheels");
- v.addWheel(new Wheel());
- } catch(TooManyWheelsException tmwe){
- break;
- }
- }
- }
- /*
- for(int i = 0; i < vehicles.size(); ++i){
- System.out.println(vehicles.get(i));
- }
- */
- } catch(Exception e){
- e.printStackTrace();
- System.out.println("Unexpected error, sorry!");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement