Need help with fixing "TreeMap cannot be resolved to a type" error in code.
This was posted in another chegg question but has errors. Was wondering if someone can please fix this.
Link to the question asked: https://www.chegg.com/homework-help/questions-and-answers/using-java-import-javautiliterator-import-javautilnosuchelementexception-public-class-pric-q44594716?trackid=undefined
I have written the updated code (changes highlighted with green color). The idea is to add a new treemap to priceQueue class to be able to satisfy the asked requirements. Now, if we look at the changes we will need to update the enqueue, deque, delete methods.
Here TreeMap maps prices to the node before that price in the queue and maps the first price (nothing before it) to null. So it will have the key of type Node and value as Type of Price. (TreeMap tree_map).
(A)enqueue method: When we enqueue a new price we need to add this to our treemap. So it will be mapped with the previous last node. And if it is the first node then it will be mapped to null.
if (isEmpty()){
first = last;
tree_map.put(price,null);
}
else
{
tree_map.put(price,oldlast);
oldlast.next = last;
}
Similarly to improve its time complexity we can directly check if the key is already present in the tree_map. And it will become a logarithmic complexity function.
(B)Deque: When we deque an element we also delete it from tree_map and We have to update the value of second element of the list as null because after deque it will become new first element of the list.
(C)Delete: To delete first of all we check if the given key ( Price) is present in our list which can be directly done using tree_map in log(n) time and if it is present then we get the value of this key which the node previous to the node to be deleted because tree_map maps a price to its previous node.
So once we get the previous node we make its next to equal to its next.next so the the the required node is deleted.
if(tree_map.containsValue(price)==true)
{
Node previous =
tree_map.get(price);
Node toBeDeleted =
previous.next;
previous.next =
previous.next.next;
toBeDeleted =
null;
return true;
}
So overall delete have a complexity if log(n).
Updated Code-
import java.util.Iterator;
import
java.util.NoSuchElementException;
public class PriceQueue implements Iterable
{
private Node first; // beginning of
queue
private Node last; // end of queue
private int n; // number of elements on
queue
// TODO - Add a TreeMap that maps prices to the node before
that price in the queue
// and maps the first price (nothing before it) to
null
TreeMap tree_map;
//
// NOTE: You will need to modify preexisting
methods to maintain the invariant on the
TreeMap
// helper linked list class
private static class Node {
private Price price;
private Node next;
}
/**
* Initializes an empty queue.
*/
public PriceQueue() {
first = null;
last = null;
n = 0;
tree_map = new TreeMap;
}
/**
* Returns true if this queue is
empty.
*
* @return {@code true} if this queue is empty; {@code
false} otherwise
*/
public boolean isEmpty() {
return first == null;
}
/**
* Returns the number of Prices in this
queue.
*
* @return the number of Prices in this queue
*/
public int size() {
return n;
}
/**
* Returns the Price least recently added to this
queue.
*
* @return the Price least recently added to this
queue
* @throws NoSuchElementException if this queue is
empty
*/
public Price peek() {
if (isEmpty()) throw new NoSuchElementException("Queue
underflow");
return first.price;
}
/**
* Adds the Price to this queue.
*
* @param Price the Price to add
*/
public void enqueue(Price price) {
if(tree_map.containsValue(price)==true)
throw
new IllegalArgumentException();
Node oldlast = last;
last = new Node();
last.price = price;
last.next = null;
if (isEmpty()){
first = last;
tree_map.put(price,null);
}
else
{
tree_map.put(price,oldlast);
oldlast.next = last;
}
n++;
}
/**
* Removes and returns the Price on this queue that
was least recently added.
*
* @return the Price on this queue that was least recently
added
* @throws NoSuchElementException if this queue is
empty
*/
public Price dequeue() {
if (isEmpty()) throw new NoSuchElementException("Queue
underflow");
Price price = first.price;
tree_map.remove(price);
tree_map.put(first.next.price,null);
first = first.next;
n--;
if (isEmpty()) last = null; // to avoid
loitering
return price;
}
/**
* Deletes a Price from the queue if it was
present.
* @param price the Price to be deleted.
* @return {@code true} if the Price was deleted and {@code
false} otherwise
*/
public boolean delete(Price price) {
// TODO implelment me!!!
// Make sure the running time is no worse
than logrithmic!!!
// You will want to use Java's TreeMap
class to map Prices to the node
// that precedes the Price in the
queue
if(tree_map.containsValue(price)==true)
{
Node previous =
tree_map.get(price);
Node toBeDeleted =
previous.next;
previous.next =
previous.next.next;
toBeDeleted =
null;
return true;
}
return false;
}
/**
* Returns a string representation of this
queue.
*
* @return the sequence of Prices in FIFO order, separated
by spaces
*/
public String toString() {
StringBuilder s = new StringBuilder();
for (Price price : this) {
s.append(price);
s.append(' ');
}
return s.toString();
}
/**
* Returns an iterator that iterates over the Prices
in this queue in FIFO order.
*
* @return an iterator that iterates over the Prices in this
queue in FIFO order
*/
public Iterator iterator() {
return new PriceListIterator(first);
}
// an iterator, doesn't implement remove() since it's
optional
private class PriceListIterator implements Iterator
{
private Node current;
public PriceListIterator(Node first) {
current = first;
}
public boolean hasNext() { return current != null;
}
public void remove() { throw new
UnsupportedOperationException(); }
public Price next() {
if (!hasNext()) throw new
NoSuchElementException();
Price price = current.price;
current = current.next;
return price;
}
}
}
Below is the price class that needs to have changes made to it.
public class Price {
private int dollars;
private int cents;
public Price(int dollars, int cents) {
if (dollars < 0 || cents < 0 || cents > 99)
throw new IllegalArgumentException();
this.dollars = dollars;
this.cents = cents;
}
public String toString() {
String answer = "$" + dollars + ".";
if (cents < 10)
answer = answer + "0" + cents;
else
answer = answer + cents;
return answer;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Price other = (Price) obj;
if (cents != other.cents)
return false;
if (dollars != other.dollars)
return false;
return true;
}
}
// Price.java
public class Price implements Comparable<Price>{
private int dollars;
private int cents;
public Price(int dollars, int cents) {
if (dollars < 0 || cents <
0 || cents > 99)
throw new
IllegalArgumentException();
this.dollars = dollars;
this.cents = cents;
}
public String toString() {
String answer = "$" + dollars +
".";
if (cents < 10)
answer = answer
+ "0" + cents;
else
answer = answer
+ cents;
return answer;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return
true;
if (obj == null)
return
false;
if (getClass() !=
obj.getClass())
return
false;
Price other = (Price) obj;
if (cents != other.cents)
return
false;
if (dollars != other.dollars)
return
false;
return true;
}
@Override
public int compareTo(Price other) {
if(dollars >
other.dollars)
return 1;
else if(dollars <
other.dollars)
return -1;
else
{
if(cents >
other.cents)
return 1;
else if(cents
< other.cents)
return -1;
else
return 0;
}
}
}
//end of Price.java
//PriceQueue.java
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.TreeMap;
public class PriceQueue implements Iterable{
private Node first; // beginning of queue
private Node last; // end of queue
private int n; // number of elements on queue
// TreeMap that maps prices to the node before that
price in the queue
// and maps the first price (nothing before it) to
null
TreeMap<Price,Node> tree_map;
//
// NOTE: You will need to modify preexisting methods
to maintain the invariant on the TreeMap
// helper linked list class
private static class Node {
private Price price;
private Node next;
}
/**
* Initializes an empty queue.
*/
public PriceQueue() {
first = null;
last = null;
n = 0;
tree_map = new
TreeMap<>();
}
/**
* Returns true if this queue is empty.
*
* @return {@code true} if this queue is empty; {@code
false} otherwise
*/
public boolean isEmpty() {
return first == null;
}
/**
* Returns the number of Prices in this queue.
*
* @return the number of Prices in this queue
*/
public int size() {
return n;
}
/**
* Returns the Price least recently added to this
queue.
*
* @return the Price least recently added to this
queue
* @throws NoSuchElementException if this queue is
empty
*/
public Price peek() {
if (isEmpty()) throw new
NoSuchElementException("Queue underflow");
return
first.price;
}
/**
* Adds the Price to this queue.
*
* @param Price the Price to add
*/
public void enqueue(Price price) {
if(tree_map.containsKey(price))
throw new
IllegalArgumentException();
Node oldlast = last;
last = new Node();
last.price = price;
last.next = null;
if (isEmpty()){
first =
last;
tree_map.put(price,null);
}
else
{
tree_map.put(price,oldlast);
oldlast.next =
last;
}
n++;
}
/**
* Removes and returns the Price on this queue that was
least recently added.
*
* @return the Price on this queue that was least
recently added
* @throws NoSuchElementException if this queue is
empty
*/
public Price dequeue() {
if (isEmpty()) throw new
NoSuchElementException("Queue underflow");
Price price = first.price;
tree_map.remove(price);
tree_map.put(first.next.price,null);
first = first.next;
n--;
if (isEmpty()) last = null; // to
avoid loitering
return
price;
}
/**
* Deletes a Price from the queue if it was
present.
* @param price the Price to be deleted.
* @return {@code true} if the Price was deleted and
{@code false} otherwise
*/
public boolean delete(Price price) {
if(tree_map.containsKey(price))
{
Node previous = tree_map.get(price);
Node toBeDeleted = previous.next;
previous.next = previous.next.next;
toBeDeleted = null;
return true;
}
return false;
}
/**
* Returns a string representation of this queue.
*
* @return the sequence of Prices in FIFO order,
separated by spaces
*/
public String toString() {
StringBuilder s = new
StringBuilder();
Iterator<Price> itr =
iterator();
while(itr.hasNext()) {
s.append(itr.next().toString());
s.append(' ');
}
return s.toString();
}
/**
* Returns an iterator that iterates over the Prices in
this queue in FIFO order.
*
* @return an iterator that iterates over the Prices in
this queue in FIFO order
*/
public Iterator<Price> iterator() {
return new
PriceListIterator(first);
}
// an iterator, doesn't implement remove() since it's
optional
private class PriceListIterator implements
Iterator<Price> {
private Node current;
public PriceListIterator(Node
first) {
current =
first;
}
public boolean hasNext() {
return current != null; }
public void remove() { throw new
UnsupportedOperationException(); }
public Price next() {
if (!hasNext())
throw new NoSuchElementException();
Price price =
current.price;
current =
current.next;
return
price;
}
}
}
//end of PriceQueue.java
// PriceQueueTester.java : Driver program to test PriceQueue
class
public class PriceQueueTester {
public static void main(String[] args)
{
PriceQueue pq = new
PriceQueue();
pq.enqueue(new Price(2,10));
pq.enqueue(new Price(10,5));
pq.enqueue(new Price(3,5));
pq.enqueue(new Price(5,12));
pq.enqueue(new Price(20,0));
System.out.println(pq);
pq.dequeue();
System.out.println(pq);
pq.delete(new Price(3,5));
System.out.println(pq);
System.out.println(pq.peek());
}
}
//end of PriceQueueTester.java
Output:

Need help with fixing "TreeMap cannot be resolved to a type" error in code. This was...
Java help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements DoubleEndedList { private Node front; // first node in list private Node rear; // last node in list private int size; // number of elements in list ////////////////////////////////////////////////// // YOU MUST IMPLEMENT THE LOCATE METHOD BELOW // ////////////////////////////////////////////////// /** * Returns the position of the node containing the given value, where * the front node is at position zero and the rear node is...
Complete P16.1 and P16.4 (Class Name: NewMethodDemo) Once complete, upload all .java files. For primary test class: Remember your header with name, date, and assignment. Also include class names that will be tested. Psuedocode (level 0 or mixture of level 0 and algorithm [do not number steps]) is required if main() contains more than simple statements (for example, your program includes constructs for decisions (if/else), loops, and methods. For Secondary class(es): Include a JavaDoc comment that describes the purpose of...
Can someone help me to figure that error I have put below. JAVA ----jGRASP exec: javac -g P4Program.java P4Program.java:94: error: package list does not exist Iterator i = new list.iterator(); ^ 1 error ----jGRASP wedge2: exit code for process is 1. ----jGRASP: operation complete. Note: Below there are two different classes that work together. Each class has it's own fuctions/methods. import java.util.*; import java.io.*; public class P4Program{ public void linkedStackFromFile(){ String content = new String(); int count = 1; File...
JAVA Have not gotten the public Iterator<Item> iterator() . Can someone explain it please? import java.util.Iterator; /* * GroupsQueue class supporting addition and removal of items * with respect to a given number of priorities and with * respect to the FIFO (first-in first-out) order for items * with the same priority. * * An example, where GroupsQueue would be useful is the airline * boarding process: every passenger gets assigned a priority, * usually a number, e.g., group 1,...
In Java You may add any classes or methods to the following as you see fit in order to complete the given tasks. Modify the LinkedList (or DoubleLinkedList) class and add a method append. append should take another LinkedList (DoubleLinkedList) as input and append that list to the end of this list. The append method should work by doing a few "arrow" adjustments on the boxes and it should not loop through the input list to add elements one at...
JAVA Modify the existing (methods already in the file may be modified but not deleted) the code to a MaxHeap and write a driver class to do the following: 1. Insert item into a Heap 2. Delete Max from the Heap 3. Display the Heap array 4. Convert an array to Heap 1,2 & 3 must all work on the same heap array. Option 4 is independent and must take in input from the user of an integer array and...
Below is the given code of implementation:
#include <string>
#include <iostream>
#include <list>
#include <cassert>
using namespace std;
class List;
class Iterator;
class Node
{
public:
/*
Constructs a node with a given data value.
@param s the data to store in this node
*/
Node(string s);
/* Destructor */
~Node() {}
private:
string data;
Node* previous;
Node* next;
friend class List;
friend class Iterator;
};
class List
{
public:
/**
Constructs an empty list.
*/
List();
/* Destructor. Deletes...
In Java Language. Modify the LinkedPostionalList class to support a method swap(p,q) that causes the underlying nodes referenced by positions p and q to be exchanged for each other. Relink the existing nodes, do not create any new nodes. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- package lists; import java.util.Iterator; import java.util.NoSuchElementException; public class LinkedPositionalList implements PositionalList { //---------------- nested Node class ---------------- /** * Node of a doubly linked list, which stores a reference to its * element and to both the previous and next...
Java: Return an array of booleans in a directed graph. Please complete the TODO section in the mark(int s) function import algs13.Bag; import java.util.HashSet; // See instructions below public class MyDigraph { static class Node { private String key; private Bag<Node> adj; public Node (String key) { this.key = key; this.adj = new Bag<> (); } public String toString () { return key; } public void addEdgeTo (Node n) { adj.add (n); } public Bag<Node> adj () { return adj;...
Since we do not want to have to rewrite this code when the element type changes, this classes uses a Comparator to assist in ordering the elements. You will need to complete the siftUpComparator() and siftDownComparator() methods in the LinkedHeap Class. siftUp §Added element may violate heap-order property §siftUp() restores order starting at added node §Processing will continue working up the tree until: úFinds properly ordered node & parent úReaches the root (reaches node without parent) siftDown §Restores heap’s order...