Advertisement
Guest User

Untitled

a guest
Apr 3rd, 2020
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.26 KB | None | 0 0
  1.  
  2. import java.util.ArrayList;
  3.  
  4. public class SimpleCollection {
  5.  
  6.     private String name;
  7.     private ArrayList<String> elements;
  8.  
  9.     public SimpleCollection(String name) {
  10.         this.name = name;
  11.         this.elements = new ArrayList<>();
  12.     }
  13.  
  14.     public void add(String element) {
  15.         this.elements.add(element);
  16.     }
  17.  
  18.     public ArrayList<String> getElements() {
  19.         return this.elements;
  20.     }
  21.    
  22.     public String toString(){
  23.        
  24.         String printOutput = "";
  25.         if(this.elements.isEmpty()){
  26.             return "The collection " + this.name + " is empty.";
  27.         }
  28.        
  29.         // adding all elements to the printOutput String.
  30.        
  31.         for(int i =0; i< this.elements.size(); i++){
  32.             printOutput+= this.elements.get(i) + "\n";
  33.         }
  34.        
  35.         // if only one element then just print it as a singular sentence ,
  36.         //    else print elements as plural.
  37.        
  38.         if(this.elements.size() == 1){
  39.             return "The collection " + this.name + " has " + this.elements.size() + " element:" + "\n" + printOutput;      
  40.         }
  41.        
  42.         return "The collection " + this.name + " has " + this.elements.size() + " elements:" + "\n" + printOutput;
  43.  
  44.     }
  45.    
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement