Question

In: Computer Science

import java.util.ArrayList; import java.util.Collections; import java.lang.Exception; public class ItemList { /** This is the main process...

import java.util.ArrayList;
import java.util.Collections;
import java.lang.Exception;

public class ItemList
{
/** This is the main process for the project */
public static void main ()
{
System.out.println("\n\tBegin Item List Demo\n");

System.out.println("Declare an ArrayList to hold Item objects");
ArrayList<Item> list = new ArrayList<Item>();

try
{
System.out.println("\n Add several Items to the list");
list.add(new Item(123, "Statue"));
list.add(new Item(332, "Painting"));
list.add(new Item(241, "Figurine"));
list.add(new Item(126, "Chair"));
list.add(new Item(411, "Model"));
list.add(new Item(55, "Watch"));

System.out.println("\nDisplay original Items list:");
listItems(list);

int result = -1;
// 1. TO DO: change the XXX to a number in the list, and YYY to a number
// not in the list (1 Pt)
System.out.println("\nLinear Search list for items XXX and YYY:");
// 2. TO DO: code a call to linearSearch with the item number (XXX)
// that is in the list; store the return in the variable result (2 Pts)

  
if(result >= 0)
// 3. TO DO: change both XXX numbers to the number searched for (1 Pt)
System.out.printf("Item XXX found at pos %d\n", result);
else
System.out.printf("Item XXX not found in list\n");

// 4. TO DO: code a call to linearSearch with the item number (yyy)
// that is not in the list; store the return in the variable result (2 Pts)
  
  
if(result >= 0)
// 5. TO DO: change both YYY to the number searched for (1 Pt)
System.out.printf("Item YYY found at pos %d\n", result);
else
System.out.printf("Item YYY not found in list\n");

System.out.println("\nSort list into Item Number sequence");
// 6. TO DO: code to sort the array using the Collections class (5 Pts)

  
System.out.println("\nDisplay the Sorted Items list:");
listItems(list);

// 7. TO DO: change the AAA to a number in the list, and BBB to a number
// not in the list (use two different numbers) (1 Pt)
System.out.println("\nBinary Search list for items AAA and BBB5:");
// 8. TO DO: code a call to binarySearch with the item number (AAA)
// that is in the list; store the return in the variable result (3 Pts)
  

if(result >= 0)
// 0. TO DO: change both AAA numbers to the number searched for (1 Pt)
System.out.printf("Item AAA found at pos %d\n", result);
else
{
System.out.printf("Item AAA not found in list\n");
System.out.printf("Should be at pos %d\n", -result -1); // note conversion
}
// 10. TO DO: code a call to binarySearch with the item number (BBB)
// that is not in the list; store the return in the variable result (3 Pts)
  
  
if(result >= 0)
// 11. TO DO change both BBB numbers to the number searched for (1 Pt)
System.out.printf("Item BBB found at pos %d\n", result);
else
{
System.out.println("Item BBB not found in list");
System.out.printf("Should be at pos %d\n", -result -1); // note conversion
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}

System.out.println("\n\tEnd Item List Demo\n");
}

/**
* This function performs a linear seach of the list
* @param list - reference to the ArrayList to be searched
* @param number - item number to seek
* @return i - index where item number wass found, -1 if not found
*/
public static int linearSearch(ArrayList<Item>list, int number)
{
for (int i = 0; i < list.size(); i++)
if(list.get(i).getItemNo() == number)
return i;
return -1;
}

/**
* This method traverses the Item list and displays the items
* @param list - reference to the ArrayList of Item Objects
*/
public static void listItems(ArrayList<Item> list)
{
for (Item item : list)
System.out.println(item.toString());
}

/**
* This recursive method finds a value in a range of a sorted ArrayList,
* using a binary search algorithm.
* @param list - reference to the ArrayList in which to search   
* @param key - the object key value to find
* @return the index at which the key occurs,
* or -n - 1 if it does not occur in the array
* n is the position in which the key object should appear   
*/
public static int binarySearch(ArrayList<Item> list, int key)
{
int low = 0;
int high = list.size() - 1;
int pos = 0;  

while (high >= low)
{
pos = (low + high) / 2;
if (key < list.get(pos).getItemNo())
high = pos - 1;
else if (key == list.get(pos).getItemNo())
return pos;
else
low = pos + 1;
}
return -low - 1;
}
}

import java.lang.Exception;

public class Item implements Comparable<Item>
{
/** The Item's identification number */
private int itemNo;
/** The Item's descriptive text */
private String itemDesc;

/**
* Constructs a default Item object
*/
public Item()
{
itemNo = 0;
itemDesc = "";
}
  
/**
* Parameter constructor for objects of class Item
* @param number - the Item's number
* @param desc - the Item's description
*/
public Item(int number, String desc) throws Exception
{
setItemNo(number);
setItemDesc(desc);
}

/**
* This method returns the Item identification number   
* @return itemNo - the Item's number
*/
public int getItemNo()
{
return itemNo;
}
  
/**
* Tis method returns the Item's description
* @return itemDesc - the Item's descriptive text
*/
public String getItemDesc()
{
return itemDesc;
}
  
/**
* This method sets the Item's identification number.
* It accepts a number change if and only if the current number is zero(0).
* Otherwise it throws an Exception
* @param number - the Item's new number
* @throw Exception, if number is invalid for this operation
*/
public void setItemNo(int number) throws Exception
{
if (itemNo == 0)
if (number > 0)
itemNo = number;
else
throw new Exception("Item number must be greater than zero(0)");   
else
throw new Exception("An existing item number cannot be changed!");
}
  
/**
* This method sets the Item's description
* @param desc - the Item's descriptive text
* @throws Exception if input desc is blank or null
*/
public void setItemDesc(String desc) throws Exception
{
if(desc.trim().length() > 0)
itemDesc = desc;
else
throw new Exception("Item description cannot be blank");
}
  
/**
* This method determines if one Item equals another
* @param other - the other Item to be matched
* @return true, if numbers are equal, false if not.
*/
public boolean equals(Item other)
{
return (itemNo == other.itemNo);
}
  
/**
* Provides the compareTo() method for the Comparable Interface
* @param otherObject - the other object for comparison
* @returns a: positive value, if this number is greater than the other
* negative value, if this number is less than the other
* zero, if the numbers are equal to each other
*/
@Override
public int compareTo(Item other)
{
return itemNo - other.itemNo;
}
  
/**
* This method overrides the toSting() method of Object
* Its purpose is to expose the data elements of the Product
* object in String form
* @return String - a string containing the Item's information
*/
@Override
public String toString()
{   
return String.format("%4d %-25s", itemNo, itemDesc);
}
}

Solutions

Expert Solution

Here is the code updated code for ItemList along with the output screenshot. Please comment if need any further assistance. Also do upvote if you are satisfied with my answer. THANKS!!

import java.util.ArrayList;
import java.util.Collections;

public class ItemList {
   public static void main(String[] args) {
       System.out.println("\n\tBegin Item List Demo\n");

       System.out.println("Declare an ArrayList to hold Item objects");
       ArrayList<Item> list = new ArrayList<Item>();

       try {
           System.out.println("\n Add several Items to the list");
           list.add(new Item(123, "Statue"));
           list.add(new Item(332, "Painting"));
           list.add(new Item(241, "Figurine"));
           list.add(new Item(126, "Chair"));
           list.add(new Item(411, "Model"));
           list.add(new Item(55, "Watch"));

           System.out.println("\nDisplay original Items list:");
           listItems(list);

           int result = -1;

// 1. TO DO: change the XXX to a number in the list, and YYY to a number
// not in the list (1 Pt)
           System.out.println("\nLinear Search list for items XXX and YYY:");
           result = linearSearch(list, 55);
// 2. TO DO: code a call to linearSearch with the item number (XXX)
// that is in the list; store the return in the variable result (2 Pts)

           if (result >= 0)
// 3. TO DO: change both XXX numbers to the number searched for (1 Pt)
               System.out.printf("Item XXX found at pos %d\n", result);
           else
               System.out.printf("Item XXX not found in list\n");

           result = linearSearch(list, 56);
// 4. TO DO: code a call to linearSearch with the item number (yyy)
// that is not in the list; store the return in the variable result (2 Pts)

           if (result >= 0)
// 5. TO DO: change both YYY to the number searched for (1 Pt)
               System.out.printf("Item YYY found at pos %d\n", result);
           else
               System.out.printf("Item YYY not found in list\n");

           System.out.println("\nSort list into Item Number sequence");
           Collections.sort(list);
// 6. TO DO: code to sort the array using the Collections class (5 Pts)

           System.out.println("\nDisplay the Sorted Items list:");
           listItems(list);

  
// 7. TO DO: change the AAA to a number in the list, and BBB to a number
// not in the list (use two different numbers) (1 Pt)
           System.out.println("\nBinary Search list for items AAA and BBB5:");
// 8. TO DO: code a call to binarySearch with the item number (AAA)
// that is in the list; store the return in the variable result (3 Pts)
           result = binarySearch(list, 55);
           if (result >= 0)
// 0. TO DO: change both AAA numbers to the number searched for (1 Pt)
               System.out.printf("Item AAA found at pos %d\n", result);
           else {
               System.out.printf("Item AAA not found in list\n");
               System.out.printf("Should be at pos %d\n", -result - 1); // note conversion
           }
// 10. TO DO: code a call to binarySearch with the item number (BBB)
// that is not in the list; store the return in the variable result (3 Pts)
           result = binarySearch(list, 56);
           if (result >= 0)
// 11. TO DO change both BBB numbers to the number searched for (1 Pt)
               System.out.printf("Item BBB found at pos %d\n", result);
           else {
               System.out.println("Item BBB not found in list");
               System.out.printf("Should be at pos %d\n", -result - 1); // note conversion
           }
       } catch (Exception e) {
           System.out.println(e.getMessage());
       }

       System.out.println("\n\tEnd Item List Demo\n");
   }

   /**
   * This function performs a linear seach of the list
   *
   * @param list - reference to the ArrayList to be searched
   * @param number - item number to seek
   * @return i - index where item number wass found, -1 if not found
   */
   public static int linearSearch(ArrayList<Item> list, int number) {
       for (int i = 0; i < list.size(); i++)
           if (list.get(i).getItemNo() == number)
               return i;
       return -1;
   }

   /**
   * This method traverses the Item list and displays the items
   *
   * @param list - reference to the ArrayList of Item Objects
   */
   public static void listItems(ArrayList<Item> list) {
       for (Item item : list)
           System.out.println(item.toString());
   }

   /**
   * This recursive method finds a value in a range of a sorted ArrayList, using a
   * binary search algorithm.
   *
   * @param list - reference to the ArrayList in which to search
   * @param key - the object key value to find
   * @return the index at which the key occurs, or -n - 1 if it does not occur in
   * the array n is the position in which the key object should appear
   */
   public static int binarySearch(ArrayList<Item> list, int key) {
       int low = 0;
       int high = list.size() - 1;
       int pos = 0;

       while (high >= low) {
           pos = (low + high) / 2;
           if (key < list.get(pos).getItemNo())
               high = pos - 1;
           else if (key == list.get(pos).getItemNo())
               return pos;
           else
               low = pos + 1;
       }
       return -low - 1;
   }
}

-----------------------------------------------OUTPUT-------------------------------------------


Related Solutions

import java.util.ArrayList; import java.util.Collections; public class BirthdayList { /** * This is the main process for...
import java.util.ArrayList; import java.util.Collections; public class BirthdayList { /** * This is the main process for class BirthdayList */ public static void main() { System.out.println("\n\tBegin Birthday List Program\n");    System.out.println("Declare an ArrayList for Birthday objects"); // 1. TO DO: Declare an ArrayList to store Birthday objects (3 Pts)       // 2. TO DO: Replace the xxx.xxxx() with the appropriate method (2 Pts) System.out.printf("\nBirthday List is empty: %s\n", xxx.xxxx() ? "True" : "False");    System.out.println("Add at least five Birthdays to...
Convert this pseudo code program into sentences. import java.util.ArrayList; import java.util.Collections; class Bulgarian {    public...
Convert this pseudo code program into sentences. import java.util.ArrayList; import java.util.Collections; class Bulgarian {    public static void main(String[] args)    {        max_cards=45;        arr->new ArraryList        col=1;        card=0;        left=max_cards;        do{            col->random number            row->new ArrayList;            for i=0 to i<col            {                card++                add card into row            }   ...
import java.util.LinkedList; import java.util.ListIterator; public class ProjectList { /** This is the main function for the...
import java.util.LinkedList; import java.util.ListIterator; public class ProjectList { /** This is the main function for the program */ public static void main() { System.out.println("\n\tBegin ProjectList demo program");    // 1. TO DO: Describe your project (1 Pt) System.out.println("Project: . . . . . . \n"); System.out.println("Create a LinkedList to store the tasks"); // 2. TO DO: Declare a LinkedList of String objects called "tasks" (1 Pt)       System.out.println("Add initial tasks into the list"); // 3. TO DO: Add initial...
import java.util.LinkedList; import java.util.Queue; import java.time.*; public class CheckOutLine { /** This is the main function...
import java.util.LinkedList; import java.util.Queue; import java.time.*; public class CheckOutLine { /** This is the main function for the program */ public static void main() { System.out.println("\n\tBegin CheckOutLine Demo\n"); System.out.println("\nCreating a Queue called \"register\" based on a LinkedList"); Queue<Customer> register = new LinkedList<Customer>();    System.out.println("\nAdding Customers to the Register queue"); // 1. TO DO: add five or more customers to the register line (5 Pts) // format: register.add(new Customer(name, checkout time));                System.out.printf("Register line has %d customers\n",...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {       ...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {        Stack<Integer> new_stack = new Stack<>();/* Start with the empty stack */        Scanner scan = new Scanner(System.in);        int num;        for (int i=0; i<10; i++){//Read values            num = scan.nextInt();            new_stack.push(num);        } System.out.println(""+getAvg(new_stack));    }     public static int getAvg(Stack s) {        //TODO: Find the average of the elements in the...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {       ...
import java.util.Stack; import java.util.Scanner; class Main { public static void main(String[] args)    {        Stack<Integer> new_stack = new Stack<>();/* Start with the empty stack */        Scanner scan = new Scanner(System.in);        int num;        for (int i=0; i<10; i++){//Read values            num = scan.nextInt();            new_stack.push(num);        }        int new_k = scan.nextInt(); System.out.println(""+smallerK(new_stack, new_k));    }     public static int smallerK(Stack s, int k) {       ...
import java.lang.UnsupportedOperationException; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc...
import java.lang.UnsupportedOperationException; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in);    // parse the number of strings int numStrings = Integer.parseInt(sc.nextLine());    // parse each string String[] stringsArray = new String[numStrings]; for (int i = 0; i < numStrings; i++) { stringsArray[i] = sc.nextLine(); }    // print whether there are duplicates System.out.println(hasDuplicates(stringsArray)); }    private static boolean hasDuplicates(String[] stringsArray) { // TODO fill this in and remove the below line...
This is the class that needs to be written... import java.util.ArrayList; /** * Deals out a...
This is the class that needs to be written... import java.util.ArrayList; /** * Deals out a game of 5-card-stud. * * @author PUT YOUR NAME HERE * @version PUT THE DATE HERE */ public class FiveCardStud { private Deck myDeck; private ArrayList<Hand> players; /** * Constructor for objects of class FiveCardStud */ /* Write a constructor for the FiveCardStud class. The constructor accepts a single integer parameter for the number of players. The number of players should be from 2...
Abstract Cart class import java.util.ArrayList; import java.util.HashMap; /** * The Abstract Cart class represents a user's...
Abstract Cart class import java.util.ArrayList; import java.util.HashMap; /** * The Abstract Cart class represents a user's cart. Items of Type T can be added * or removed from the cart. A hashmap is used to keep track of the number of items * that have been added to the cart example 2 apples or 4 shirts. * @author Your friendly CS Profs * @param -Type of items that will be placed in the Cart. */ public abstract class AbstractCart {...
import java.util.ArrayList; public class Workouts { public enum Muscle {ABS, BACK, BICEPS, CHEST, FOREARM, GLUTES, LOWERLEG,...
import java.util.ArrayList; public class Workouts { public enum Muscle {ABS, BACK, BICEPS, CHEST, FOREARM, GLUTES, LOWERLEG, SHOULDER, TRICEPS, UPPERLEG, NONE} // Why didn't I have to declare this static? public enum Equipment {BARBELL, BODYWEIGHT, DUMBBELL, CABLE, HAMMERSTRENGTH}    private final ArrayList<Workout> workoutList = new ArrayList<Workout>();    // You will need to create a number of methods for the inner class. You are not limited to    // only the methods listed inside this class.    private class Workout {   ...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT