- import java.util.Arrays;
- public class Train {
- private String name;
- private int locomotive;
- private int[] freightCars = { };
- public Train(String name, int locomotive) {
- if (name == null) {
- throw new NullPointerException("Name can't be null");
- }
- else {
- this.name = name;
- }
- if (locomotive < 0) {
- throw new IllegalArgumentException("locomotive can't be negative");
- }
- else {
- this.locomotive = locomotive;
- }
- }
- public int[] getFreightCars() {
- return Arrays.copyOf(freightCars, freightCars.length);
- }
- public String getName() {
- return name;
- }
- public void setName(String n) {
- if (n == null) {
- throw new NullPointerException("Name can't be null");
- }
- else {
- this.name = n;
- }
- }
- public int getLocomotive() {
- return locomotive;
- }
- public void setLocomotive(int p) {
- if (p < 0) {
- throw new IllegalArgumentException("locomotive can't be negative");
- }
- else {
- this.locomotive = p;
- }
- }
- public int getTotalWeightOfCars() {
- int total = 0;
- for (int n : this.freightCars) {
- total += n;
- }
- return total;
- }
- public int getNumbersOfCars() {
- return this.freightCars.length;
- }
- public int maxSpeed() {
- int speed = this.locomotive - this.getTotalWeightOfCars();
- if (speed >= 150) {
- return 150;
- }
- else if (speed < 0) {
- return 0;
- }
- else {
- return speed;
- }
- }
- public void removeAllCars() {
- this.freightCars = new int[] { };
- }
- public void addCars(int... weights) {
- if (weights == null) {
- throw new NullPointerException(null);
- }
- int [] temp = new int[this.freightCars.length + weights.length];
- for (int i = 0; i < this.freightCars.length; i++) {
- temp[i] = this.freightCars[i];
- }
- for (int i = 0; i < weights.length; i++) {
- temp[this.getNumbersOfCars() + i] = weights[i];
- }
- this.freightCars = temp;
- }
- public void mergeCars(Train other) {
- this.locomotive = this.locomotive + other.locomotive;
- other.locomotive = 0;
- this.addCars(other.freightCars);
- other.removeAllCars();
- }
- }
[text] yessir
Viewer
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
Editor
You can edit this paste and save as new:
File Description
- yessir
- Paste Code
- 30 Sep-2022
- 2.12 Kb
You can Share it: