Advertisement
Cieslin

JavaArrayList_1

Jan 6th, 2018
288
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.94 KB | None | 0 0
  1. package com.cieslin;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class Main {
  6.     private static Scanner scanner = new Scanner(System.in);
  7.     private static GroceryList groceryList = new GroceryList();
  8.     public static void main(String[] args) {
  9.         groceryList.addGroceryItem("Bread");
  10.         groceryList.addGroceryItem("Cheess");
  11.         groceryList.addGroceryItem("Milk");
  12.         groceryList.printGroceryList();
  13.         groceryList.addGroceryItem("Egg");
  14.         groceryList.printGroceryList();
  15.         groceryList.modifyGroceryItem(1, "Water");
  16.         System.out.println(groceryList.findItem("Egg"));
  17.         groceryList.printGroceryList();
  18.         groceryList.removeGroceryItem(1);
  19.         groceryList.removeGroceryItem(2);
  20.         groceryList.printGroceryList();
  21.         groceryList.removeGroceryItem(1);
  22.         groceryList.printGroceryList();
  23.  
  24.     }
  25. }
  26. /////////////////////////////////////////////////////////////////////////////////////////////////////
  27. package com.cieslin;
  28.  
  29. import java.util.ArrayList;
  30.  
  31. public class GroceryList {
  32.     private ArrayList<String> groceryList = new ArrayList<String>();
  33.  
  34.     public void addGroceryItem(String item){
  35.         groceryList.add(item);
  36.     }
  37.  
  38.     public void printGroceryList(){
  39.         System.out.println("You have " + groceryList.size() + " items in your grocery list");
  40.         for(int i = 0; i < groceryList.size(); i++)
  41.             System.out.println((i+1) + ". " + groceryList.get(i));
  42.     }
  43.  
  44.     public void modifyGroceryItem(int position, String newItem){
  45.         groceryList.set(position, newItem);
  46.     }
  47.  
  48.     public void removeGroceryItem(int position){
  49.         groceryList.remove(position-1);
  50.     }
  51.  
  52.     public String findItem(String searchItem){
  53.         //boolean exists = groceryList.contains(searchItem);
  54.         int position = groceryList.indexOf(searchItem);
  55.         if(position >= 0)
  56.             return groceryList.get(position);
  57.         return null;
  58.  
  59.     }
  60.  
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement