This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am having some issues with my linked list class. I am currently trying to print my favorite bands in the assigned order I gave them, but I am either coming up with the program just prints null or just the band names in the wrong order. I am confused as to why or what I am missing. Any help would be appreciated.
The output I currently get is
Exception in thread "main" java.lang.NullPointerException
at project2.jacobLinkedList.toString(MetalMasher.java:171)
at java.lang.String.valueOf(Unknown Source)
at java.lang.StringBuilder.append(Unknown Source)
at project2.MetalMasher.main(MetalMasher.java:44)
The file is
import java.util.Collections;
import java.util.List;
public class MetalMasher {
public static jacobLinkedList jacobList;
#SuppressWarnings("unchecked")
public static <T> void main(String[] args) {
// this is the default constructor.
jacobList = new jacobLinkedList();
// add elements to the list.
jacobList.add("MegaDeth",1993);
jacobList.add("Slayer",1992);
jacobList.add("Scar Symmetry",2002);
jacobList.add("Gojira",2004);
jacobList.add("Amon Amarth",1997);
System.out.println("Print: jacobList:" + jacobList);
System.out.println(".size():" + jacobList.size());
System.out.println(".remove(2):" + jacobList.remove(2) + " (element removed)");
System.out.println("Print again:" + jacobList);
System.out.println(".remove(1):" + jacobList.remove(1) + " (element removed)");
System.out.println("Print again:" + jacobList);
System.out.println(".remove(1):" + jacobList.remove(1) + " (element removed)");
System.out.println("Print again:" + jacobList);
}
}
class jacobLinkedList {
private static int counter;
private Node head;
// Default constructor
public jacobLinkedList() {
}
// appends the specified element to the end of this list.
public void add(Object data, int i) {
// Initialize Node only incase of 1st element
if (head == null) {
head = new Node(data, i);
}
Node jacobTemp = new Node(data, i);
Node jacobCurrent = head;
if (jacobCurrent != null) {
while (jacobCurrent.getNext() != null) {
jacobCurrent = jacobCurrent.getNext();
}
jacobCurrent.setNext(jacobTemp);
}
// increment the number of elements variable
incrementCounter();
}
private static int getCounter() {
return counter;
}
private static void incrementCounter() {
counter++;
}
private void decrementCounter() {
counter--;
}
// inserts the specified element at the specified position in this list
public void insert(Object data, int i) {
Node jacobTemp = new Node(data, i);
Node jacobCurrent = head;
if (jacobCurrent != null) {
// crawl to the requested index or the last element in the list, whichever comes first
for (int z = 0; z < i && jacobCurrent.getNext() != null; i++) {
jacobCurrent = jacobCurrent.getNext();
}
}
// set the new node's next-node reference to this node's next-node reference
jacobTemp.setNext(jacobCurrent.getNext());
// reference to new node
jacobCurrent.setNext(jacobTemp);
// increment the number of elements variable
incrementCounter();
}
// removes the element at the specified position in this list.
public boolean remove(int index) {
// if the index is out of range, exit
if (index < 1 || index > size())
return false;
Node jacobCurrent = head;
if (head != null) {
for (int i = 0; i < index; i++) {
if (jacobCurrent.getNext() == null)
return false;
jacobCurrent = jacobCurrent.getNext();
}
jacobCurrent.setNext(jacobCurrent.getNext().getNext());
decrementCounter();
return true;
}
return false;
}
// returns the number of elements in this list.
public int size() {
return getCounter();
}
public String toString() {
String output = "";
if (head != null) {
Node jacobCurrent = head.getNext();
while (jacobCurrent != null) {
output += "[" + jacobCurrent.getData().getClass() + "]";
jacobCurrent = jacobCurrent.getNext();
}
}
return output;
}
public class Node {
// reference to the next node in the chain
Node next;
Object data;
// Node constructor
public Node(Object dataValue, Class<Integer> class1) {
next = (Node) null;
data = dataValue;
}
// Node contructor to point towards
#SuppressWarnings("unused")
public Node(Object dataValue, Node ranking) {
next = ranking;
data = dataValue;
}
public Node(Object data, int i) {
// TODO Auto-generated constructor stub
}
public Object getData() {
return data;
}
#SuppressWarnings("unused")
public void setData(Object dataValue) {
data = dataValue;
}
public Node getNext() {
return next;
}
public void setNext(Node nextValue) {
next = nextValue;
}
}
}
From the looks of it, it's most likely the getData method in the Node object that is returning null. That's because you forgot to set the data in the constructor with an object and integer.
public Node(Object data, int i) {
this.data = data;
}
I don't know what the integer is for though.
in toString() method in this line:
output += "[" + jacobCurrent.getData().getClass() + "]";
You need to check when getData() returns null, which it does in most cases for your inputs.
Solution is to check for null before adding string to output. Don't know what you want with it, either add string "null" or skip such cases or fix inputs.
Use:
/**
* Created by MR on 4/27/2016.
*/
import java.util.Collections;
import java.util.List;
public class Test {
public static jacobLinkedList jacobList;
#SuppressWarnings("unchecked")
public static <T> void main(String[] args) {
// this is the default constructor.
jacobList = new jacobLinkedList();
// add elements to the list.
jacobList.add("MegaDeth",1993);
jacobList.add("Slayer",1992);
jacobList.add("Scar Symmetry",2002);
jacobList.add("Gojira",2004);
jacobList.add("Amon Amarth",1997);
System.out.println("Print: jacobList:" + jacobList);
System.out.println(".size():" + jacobList.size());
System.out.println(".remove(2):" + jacobList.remove(2) + " (element removed)");
System.out.println("Print again:" + jacobList);
System.out.println(".remove(1):" + jacobList.remove(1) + " (element removed)");
System.out.println("Print again:" + jacobList);
System.out.println(".remove(1):" + jacobList.remove(1) + " (element removed)");
System.out.println("Print again:" + jacobList);
}
}
class jacobLinkedList {
private static int counter;
private Node head;
// Default constructor
public jacobLinkedList() {
}
// appends the specified element to the end of this list.
public void add(Object data, int i) {
// Initialize Node only incase of 1st element
if (head == null) {
head = new Node(data, i);
}
Node jacobTemp = new Node(data, i);
Node jacobCurrent = head;
if (jacobCurrent != null) {
while (jacobCurrent.getNext() != null) {
jacobCurrent = jacobCurrent.getNext();
}
jacobCurrent.setNext(jacobTemp);
}
// increment the number of elements variable
incrementCounter();
}
private static int getCounter() {
return counter;
}
private static void incrementCounter() {
counter++;
}
private void decrementCounter() {
counter--;
}
// inserts the specified element at the specified position in this list
public void insert(Object data, int i) {
Node jacobTemp = new Node(data, i);
Node jacobCurrent = head;
if (jacobCurrent != null) {
// crawl to the requested index or the last element in the list, whichever comes first
for (int z = 0; z < i && jacobCurrent.getNext() != null; i++) {
jacobCurrent = jacobCurrent.getNext();
}
}
// set the new node's next-node reference to this node's next-node reference
jacobTemp.setNext(jacobCurrent.getNext());
// reference to new node
jacobCurrent.setNext(jacobTemp);
// increment the number of elements variable
incrementCounter();
}
// removes the element at the specified position in this list.
public boolean remove(int index) {
// if the index is out of range, exit
if (index < 1 || index > size())
return false;
Node jacobCurrent = head;
if (head != null) {
for (int i = 0; i < index; i++) {
if (jacobCurrent.getNext() == null)
return false;
jacobCurrent = jacobCurrent.getNext();
}
jacobCurrent.setNext(jacobCurrent.getNext().getNext());
decrementCounter();
return true;
}
return false;
}
// returns the number of elements in this list.
public int size() {
return getCounter();
}
public String toString() {
String output = "";
if (head != null) {
Node jacobCurrent = head.getNext();
while (jacobCurrent.getData() != null) {
output += "[" + jacobCurrent.getData().getClass() + "]";
jacobCurrent = jacobCurrent.getNext();
}
}
return output;
}
public class Node {
// reference to the next node in the chain
Node next;
Object data;
// Node constructor
public Node(Object dataValue, Class<Integer> class1) {
next = (Node) null;
data = dataValue;
}
// Node contructor to point towards
#SuppressWarnings("unused")
public Node(Object dataValue, Node ranking) {
next = ranking;
data = dataValue;
}
public Node(Object data, int i) {
// TODO Auto-generated constructor stub
}
public Object getData() {
return data;
}
#SuppressWarnings("unused")
public void setData(Object dataValue) {
data = dataValue;
}
public Node getNext() {
return next;
}
public void setNext(Node nextValue) {
next = nextValue;
}
}
}
I hope this helps you
Related
So I am working on a project involving Linked Lists. We have to make the Nodes and the Linked Lists ourselves (not allowed to use the Java provided ones). As part of the project, I am making a list that will automatically adjust itself upon certain criteria (when the word being entered is the same as one that already exists, move that Node to the front of the list). My code appears to run fine but after a certain amount of time, it just stops running. When I try debugging it, Eclipse just suspends the process at that point and I cannot figure out why as it provides absolutely no feedback at all. It appears to be on one of the while loops but I can't seem to figure out why. Any help would be greatly appreciated. The code is relatively long so I will paste it below this wall of text. I am not super experienced in programming yet so you might notice some mistakes/annoyances.
SelfAdjustingListOne.java
public class SelfAdjustingListOne extends UnsortedList
{
public SelfAdjustingListOne()
{
super();
}
public SelfAdjustingListOne(long timer)
{
super(timer);
}
public void adjustingAdd(Node input)
{
// If there's nothing in the list, make this the first and last node
if (getFront() == null)
{
setFront(input);
setBack(input);
input.setIndex(0);
} else if (sameWord(input) != null)
{
// If the word already exists, increment the word count and send that node to
// the front of the list
Node sameString = sameWord(input), current = getFront(), previous;
try
{
// Will return null if sameString is the first node on the list
previous = getByIndex(sameString.getIndex() - 1);
} catch (NullPointerException e)
{
previous = null;
}
// If sameString is the first node, no link needs to be set
if (previous != null)
previous.setLink(sameString.getLink());
// Link the node we are moving to the front node
sameString.setLink(getFront());
// Set the value of the front node to the node we are moving
setFront(sameString);
// Increment its count
sameString.plusCount();
// While the current node exists and has not surpassed the previous location of
// the node we moved, increment the index value of each node by 1
while (current != null && current.getIndex() != sameString.getIndex())
{
current.plusIndex();
current = current.getLink();
}
// Set the new front node's index to 0 (Beginning of the list)
sameString.setIndex(0);
plusComparisons();
plusComparisons();
} else
{
// If the list has at least one node and the word being added doesn't exist, add
// this node to the front of the list
input.setLink(getFront());
Node current = getFront();
while (current != null)
{
current.plusIndex();
current = current.getLink();
}
setFront(input);
input.setIndex(0);
plusComparisons();
plusNodeChanges();
plusNodeChanges();
}
}
}
UnsortedList.java
import java.text.DecimalFormat;
public class UnsortedList
{
private Node front;
private Node back;
private Long timer;
private int numOfComparisons;
private int nodeChanges;
public UnsortedList()
{
}
public UnsortedList(long timer)
{
this.timer = timer;
}
public void addBack(Node input)
{
if (front == null)
{
setFront(input);
setBack(input);
input.setIndex(0);
} else if (sameWord(input) != null)
{
Node sameString = sameWord(input);
sameString.plusCount();
numOfComparisons += 2;
} else
{
getBack().setLink(input);
input.setIndex(back.getIndex() + 1);
setBack(input);
numOfComparisons++;
nodeChanges += 2;
}
}
public void addFront(Node input)
{
if (front == null)
{
setFront(input);
setBack(input);
input.setIndex(0);
} else if (sameWord(input) != null)
{
Node sameString = sameWord(input);
sameString.plusCount();
numOfComparisons += 2;
} else
{
input.setLink(front);
Node current = front;
while (current != null)
{
current.plusIndex();
current = current.getLink();
}
setFront(input);
input.setIndex(0);
numOfComparisons++;
nodeChanges += 2;
}
}
public void remove(int index)
{
Node current = front;
do
{
if (current.getIndex() == index - 1)
{
if (current.getLink().getLink() != null)
{
current.getLink().setIndex(-1);
current.setLink(current.getLink().getLink());
Node currentIndexNode = current.getLink();
while (currentIndexNode != null)
{
currentIndexNode.minusIndex();
currentIndexNode = currentIndexNode.getLink();
}
} else
{
current.getLink().setIndex(-1);
current.setLink(null);
}
}
current = current.getLink();
} while (!current.isEqual(back));
}
public void setFront(Node input)
{
front = input;
}
public void setBack(Node input)
{
back = input;
}
public Node getFront()
{
return front;
}
public Node getBack()
{
return back;
}
public Node getByIndex(int index) throws NullPointerException
{
Node current = front, currentIndexNode = current.getLink();
while (current != null)
{
do
{
if (current.getIndex() == index)
return current;
current = currentIndexNode;
currentIndexNode = currentIndexNode.getLink();
} while (currentIndexNode != null);
}
return null;
}
public Node getByWord(String word) throws NullPointerException
{
Node current = front, currentIndexNode = current.getLink();
while (current != null)
{
do
{
if (current.getWord().equalsIgnoreCase(word))
return current;
current = currentIndexNode;
currentIndexNode = currentIndexNode.getLink();
} while (currentIndexNode != null);
}
return null;
}
public int totalWords()
{
Node current = front;
int totalWords = 0;
while (current != null)
{
totalWords += current.getCount();
current = current.getLink();
}
return totalWords;
}
public int totalUniqueWords()
{
Node current = front;
int totalUniqueWords = 0;
while (current != null)
{
totalUniqueWords++;
current = current.getLink();
}
return totalUniqueWords;
}
public int totalNumOfComparisons()
{
return numOfComparisons;
}
public int totalNodeChanges()
{
return nodeChanges;
}
public String totalTimeElapsed()
{
if (timer == null)
return "This is an untimed list";
DecimalFormat threePlaces = new DecimalFormat("#0.000");
return threePlaces.format((System.nanoTime() - timer) * Math.pow(10, -9)) + " seconds";
}
public void plusComparisons()
{
numOfComparisons++;
}
public void plusNodeChanges()
{
nodeChanges++;
}
protected Node sameWord(Node input)
{
Node current = front;
while (current != null)
{
if (current.getWord().equalsIgnoreCase(input.getWord()))
return current;
current = current.getLink();
}
return null;
}
}
Node.java
public class Node
{
private Node link;
private String word;
private int count = 1;
private int index = -1;
public Node(String word)
{
this.word = word;
}
public Node getLink()
{
return link;
}
public String getWord()
{
return word;
}
public int getCount()
{
return count;
}
public int getIndex()
{
return index;
}
public void setLink(Node input)
{
link = input;
}
public void setWord(String input)
{
word = input;
}
public void setCount(int input)
{
count = input;
}
public void setIndex(int input)
{
index = input;
}
public void plusCount()
{
count++;
}
public void plusIndex()
{
index++;
}
public void minusIndex()
{
index--;
}
public boolean isEqual(Node input)
{
if (input.getWord().equalsIgnoreCase(this.word))
return true;
return false;
}
}
The code which runs the SelfAdjustingListOne
public static SelfAdjustingListOne salo;
public static void main(String[] args)
{
System.out.println("Running fifth pass...");
System.out.println("Time to execute fifth pass: " + pass5());
}
public static String pass5()
{
salo = new SelfAdjustingListOne(System.nanoTime());
try
{
Scanner scanner = new Scanner(new File(fileDirectory + fileNames[0] + fileExtension));
while (scanner.hasNext())
{
String s = scanner.next();
s.replaceAll("^[^a-zA-Z0-9]+", "");
s.replaceAll("[^a-zA-Z0-9]+$", "");
if (s.length() == 1 || s.length() == 0)
{
if (!Character.isAlphabetic(s.charAt(0)) && !Character.isDigit(s.charAt(0)))
continue;
}
salo.adjustingAdd(new Node(s));
}
scanner.close();
} catch (FileNotFoundException e)
{
System.out.println("No file found matching that name/directory");
}
return salo.totalTimeElapsed();
}
The file it says it's reading in is the A Bee Movie Script which I cannot post because of the max length of a post but any text file should do.
I figured it out with a little help from samabcde.
This block of code right here needed to be changed from this:
if (previous != null)
previous.setLink(sameString.getLink());
// Link the node we are moving to the front node
sameString.setLink(getFront());
// Set the value of the front node to the node we are moving
setFront(sameString);
To this:
if(sameString != getFront())
{
sameString.setLink(getFront());
// Set the value of the front node to the node we are moving
setFront(sameString);
}
It was linking to itself because it never checked to see if the node it was setting the link of WAS ALREADY the first node in the list, therefore setting the link equal to itself.
I am currently trying to understand Singly linked lists.
I don't understand some of the code in the SinglyLinkedList.java class. How can the Node class be called and then assigned like: private Node first;
I would have thought that you would have to do something like this
Node<T> help =new Node<>();
help = first;
If someone could explain, or provide me to a link that would help me, it would be much appreciated.
Thanks!
public class Node<T> {
public T elem;
public Node<T> next;
public Node(T elem) {
this.elem = elem;
next = null;
}
public Node(T elem, Node<T> next) {
this.elem = elem;
this.next = next;
}
#Override
public String toString() {
return "Node{" + "elem=" + elem + '}';
}
}
package list;
/**
*
* #author dcarr
*/
public class SinglyLinkedList<T> implements List<T> {
private Node<T> first;
private Node<T> last;
public SinglyLinkedList() {
first = null;
last = null;
}
#Override
public boolean isEmpty() {
return first == null;
}
#Override
public int size() {
if (isEmpty()){
return 0;
} else {
int size = 1;
Node<T> current = first;
while(current.next != null){
current = current.next;
size++;
}
return size;
}
}
#Override
public T first() {
return first.elem;
}
#Override
public void insert(T elem) {
// if there is nothing in the list
if (isEmpty()){
first = new Node<>(elem);
last = first;
// if the list has elements already
} else {
// the new element will be the next of what was the last element
last.next = new Node<>(elem);
last = last.next;
}
}
#Override
public void remove(T elem) {
if (!isEmpty()){
int index = 0;
Node<T> current = first;
while (current != null && current.elem != elem){
current= current.next;
index++;
}
remove(index);
}
}
#Override
public String toString() {
if (isEmpty()){
return "Empty List";
} else {
String str = first.elem.toString() + " ";
Node<T> current = first;
while(current.next != null){
current = current.next;
str += current.elem.toString() + " ";
}
return str;
}
}
#Override
public void insertAt(int index, T e) {
if (index == 0){
first = new Node<>(e, first);
if (last == null){
last = first;
}
return;
}
Node<T> pred = first;
for (int i = 0; i < index-1; i++) {
pred = pred.next;
}
pred.next = new Node<>(e, pred.next);
System.out.println(pred);
if (pred.next.next == null){
// what does this mean pred.next is?
last = pred.next;
}
}
#Override
public void remove(int index) {
if (index < 0 || index >= size()){
throw new IndexOutOfBoundsException();
} else if (isEmpty()){
return;
}
if (index == 0){
first = first.next;
if (first == null){
last = null;
}
return;
}
Node<T> pred = first;
for (int i = 1; i <= index-1; i++) {
pred = pred.next;
}
// remove pred.next
pred.next = pred.next.next;
if (pred.next == null){
last = pred;
}
}
}
The first field is automatically initialized to null:
private Node<T> first;
I assume there will be some method to add an element at the end like so:
public void add(T element) {
if (first == null) {
first = new Node<T>(element);
last = first;
}
else {
last.next = new Node<>(element);
last = last.next;
}
}
So when you create a new SinglyLinkedList:
SinglyLinkedList<String> sillyList = new SinglyLinkedList<>();
The first and last fields both hold a null reference.
Note that the first method will cause a NullPointerException at this point. A better implementation would be:
#Override
public Optional<T> first() {
if (first != null) {
return Optional.ofNullable(first.elem);
}
else {
return Optional.empty();
}
}
Now if you add an element:
sillyList.add("Adam");
The code executed in the add method is:
first = new Node<>(elem);
last = first;
So first points to a new Node instance with an elem field holding the value "Adam". And last points to that same Node instance.
Some of the methods in this class I would implement differently, for example:
#Override
public void remove(int index) {
if (index < 0) {
throw new IndexOutOfBoundsException("Index cannot be negative");
}
else if (index == 0 && first != null) {
first = null;
last = null;
}
else {
Node<T> curr = new Node<>("dummy", first);
int c = 0;
while (curr.next != null) {
if (c == index) {
curr.next = curr.next.next;
if (curr.next == null) {
last = curr;
}
return;
}
curr = curr.next;
c++;
}
throw new IndexOutOfBoundsException(String.valueOf(c));
}
Also, some of the methods don't actually exist in the java.util.List interface, like insert, insertAt and first. So these methods must not have the #Override annotation.
This is for a class assignment; I currently have a single-linked list and need to convert it into a doubly-linked list. Currently, the list is a collection of historical battles.
What in this program needs to be changed to turn this into a double-linked list? I feel like I'm really close, but stuck on a certain part (What needs to be changed in the 'add' part)
public static MyHistoryList HistoryList;
public static void main(String[] args) {
//Proof of concept
HistoryList = new MyHistoryList();
HistoryList.add("Battle of Vienna");
HistoryList.add("Spanish Armada");
HistoryList.add("Poltava");
HistoryList.add("Hastings");
HistoryList.add("Waterloo");
System.out.println("List to begin with: " + HistoryList);
HistoryList.insert("Siege of Constantinople", 0);
HistoryList.insert("Manzikert", 1);
System.out.println("List following the insertion of new elements: " + HistoryList);
HistoryList.remove(1);
HistoryList.remove(2);
HistoryList.remove(3);
System.out.println("List after deleting three things " + HistoryList);
}
}
class MyHistoryList {
//setting up a few variables that will be needed
private static int counter;
private Node head;
This is the private class for the node, including some getters and setters. I've already set up 'previous', which is supposed to be used in the implementation of the doubly-linked list according to what I've already googled, but I'm not sure how to move forward with the way MY single-list is set up.
private class Node {
Node next;
Node previous;
Object data;
public Node(Object dataValue) {
next = null;
previous = null;
data = dataValue;
}
public Node(Object dataValue, Node nextValue, Node previousValue) {
previous = previousValue;
next = nextValue;
data = dataValue;
}
public Object getData() {
return data;
}
public void setData(Object dataValue) {
data = dataValue;
}
public Node getprevious() {
return previous;
}
public void setprevious(Node previousValue) {
previous = previousValue;
}
public Node getNext() {
return next;
}
public void setNext(Node nextValue) {
next = nextValue;
}
}
This adds elements to the list. I think I need to change this part in order to make this into a doubly-linked list, but don't quite understand how?
public MyHistoryList() {
}
// puts element at end of list
public void add(Object data) {
// just getting the node ready
if (head == null) {
head = new Node(data);
}
Node Temp = new Node(data);
Node Current = head;
if (Current != null) {
while (Current.getNext() != null) {
Current = Current.getNext();
}
Current.setNext(Temp);
}
// keeping track of number of elements
incrementCounter();
}
private static int getCounter() {
return counter;
}
private static void incrementCounter() {
counter++;
}
private void decrementCounter() {
counter--;
}
This is just tostring, insertion, deletion, and a few other things. I don't believe anything here needs to be changed to make it a doubly linked list?
public void insert(Object data, int index) {
Node Temp = new Node(data);
Node Current = head;
if (Current != null) {
for (int i = 0; i < index && Current.getNext() != null; i++) {
Current = Current.getNext();
}
}
Temp.setNext(Current.getNext());
Current.setNext(Temp);
incrementCounter();
}
//sees the number of elements
public Object get(int index)
{
if (index < 0)
return null;
Node Current = null;
if (head != null) {
Current = head.getNext();
for (int i = 0; i < index; i++) {
if (Current.getNext() == null)
return null;
Current = Current.getNext();
}
return Current.getData();
}
return Current;
}
// removal
public boolean remove(int index) {
if (index < 1 || index > size())
return false;
Node Current = head;
if (head != null) {
for (int i = 0; i < index; i++) {
if (Current.getNext() == null)
return false;
Current = Current.getNext();
}
Current.setNext(Current.getNext().getNext());
decrementCounter();
return true;
}
return false;
}
public int size() {
return getCounter();
}
public String toString() {
String output = "";
if (head != null) {
Node Current = head.getNext();
while (Current != null) {
output += "[" + Current.getData().toString() + "]";
Current = Current.getNext();
}
}
return output;
}
}
Hi I am currently working on a queue wait time simultaion, over the course of 12 hours that adds a random number of people per line every minute while removing three from the front every minute as well. After the twelve hours are over i will average the rate in which they entered and exited the line. I need to perform this 50 times to get a more accurate model simulation. I do not currently know how to properly implement this. If i could get some pointers on where to begin it would be most appreciated.
Linked List Class
public class LinkedListQueue<E>{
private Node<E> head;
private Node<E> tail;
private int size;
public LinkedListQueue() {
}
public void enqueue(E element) {
Node newNode = new Node(element, null);
if (size == 0) {
head = newNode;
} else {
tail.setNextNode(newNode);
}
tail = newNode;
size++;
}
public E dequeue() {
if (head != null) {
E element = head.getElement();
head = head.getNextNode();
size--;
if (size == 0) {
tail = null;
}
return element;
}
return null;
}
public E first() {
if (head != null) {
return head.getElement();
}
return null;
}
public int getSize() {
return size;
}
public void print() {
if (head != null) {
Node currentNode = head;
do {
System.out.println(currentNode.toString());
currentNode = currentNode.getNextNode();
} while (currentNode != null);
}
System.out.println();
}
}
Node Class
public class Node<E>{
private E element;
private Node<E> next;
public Node(E element, Node next) {
this.element = element;
this.next = next;
}
public void setNextNode(Node next) {
this.next = next;
}
public Node<E> getNextNode() {
return next;
}
public E getElement() {
return element;
}
public String toString() {
return element.toString();
}
}
Simulation Class
import java.util.Random;
public class Simulation {
private int arrivalRate;
//you'll need other instance variables
public Simulation(int arrivalRate, int maxNumQueues) {
this.arrivalRate = arrivalRate;
}
public void runSimulation() {
//this is an example for using getRandomNumPeople
//you are going to remove this whole loop.
for (int i = 0; i < 10; i++) {
int numPeople = getRandomNumPeople(arrivalRate);
System.out.println("The number of people that arrived in minute " + i + " is: " + numPeople);
}
}
//Don't change this method.
private static int getRandomNumPeople(double avg) {
Random r = new Random();
double L = Math.exp(-avg);
int k = 0;
double p = 1.0;
do {
p = p * r.nextDouble();
k++;
} while (p > L);
return k - 1;
}
//Don't change the main method.
public static void main(String[] args) {
Simulation s = new Simulation(18, 10);
s.runSimulation();
}
}
It looks like you haven't started this assignment at all.
First, start with the main() method. A new Simulation object is created. Follow the constructor call to new Simulation(18, 10). For starters, you will see that the constructor is incomplete
public Simulation(int arrivalRate, int maxNumQueues) {
this.arrivalRate = arrivalRate;
// missing the handling of maxNumQueues
}
So, for starters, you probably want to define a new variable of type integer (since that is what is the type of maxNumQueues according to the Simulation constructor) in the Simulation class. From there, you obviously want to get back into the constructor and set your new variable to reference the constructor call.
Example:
public class Simulation {
private int arrivalRate;
private int maxNumQueues; // keep track of the maxNumQueues
public Simulation(int arrivalRate, int maxNumQueues) {
this.arrivalRate = arrivalRate;
this.maxNumQueues = maxNumQueues; // initialize our new local variable maxNumQueues
}}
I am learning Java SE and am currently at simple linked lists (page 687/1047 of Savitch's Absolute Java).
I am stuck at instantiating the LinkList in the main method of my demo class:
LinkedList1 list = new LinkedList1();
I tried using breakpoint and it indicates a ReflectiveOperationException.
This is the code:
public class Node1
{
private String item;
private int count;
private Node1 link;
public Node1()
{
link = null;
item = null;
count = 0;
}
public Node1(String newItem, int newCount, Node1 linkValue)
{
setData(newItem, newCount);
link = linkValue;
}
public void setData(String newItem, int newCount)
{
item = newItem;
count = newCount;
}
public void setLink(Node1 newLink)
{
link = newLink;
}
public String getItem()
{
return item;
}
public int getCount()
{
return count;
}
public Node1 getLink()
{
return link;
}
}
This is the LinkedList1 class:
public class LinkedList1
{
private Node1 head;
public LinkedList1()
{
head = null;
}
/**
* Adds a node at the start of the list with the specified data.
* The added node will be the first node in the list.
*/
public void add(String itemName, int itemCount)
{
head = new Node1(itemName, itemCount, head);
}
/**
* Removes the head node and returns true if the list contains at least
* one node. Returns false if the list is empty.
*/
public boolean deleteHeadNode()
{
if (head != null)
{
head = head.getLink();
return true;
}
else
return false;
}
/**
* Returns the number of nodes in the list.
*/
public int size()
{
int count = 0;
Node1 position = head;
while (position != null)
{
count++;
head = position.getLink();
}
return count;
}
public boolean contains(String item)
{
return (find(item) != null);
}
/**
* Finds the first node containing the target item, and returns a
* reference to that node. If the target is not in the list, null is returned.
*/
public Node1 find(String target)
{
Node1 position = head;
String itemAtPosition;
while(position != null)
{
itemAtPosition = position.getItem();
if(itemAtPosition.equals(target))
{
return position;
}
position = position.getLink();
}
return null; //target was not found
}
public void outputList()
{
Node1 position = head;
while (position != null)
{
System.out.println(position.getItem() + " " + position.getCount());
position = position.getLink();
}
}
}
I think that the problem has something to do with the constructor of Node1 having the member link of type Node1. I'm trying to understand how these data structures work and not just resort to using the built-in ArrayList(& APIs) for my projects. Can you guys have a look and point me in the right direction. Any help would be very much appreciated.
This is my main method.
public class LinkedListDemo
{
public static void main(String[] args)
{
try
{
LinkedList1 list = new LinkedList1();
list.add("apples", 1);
list.add("bananas", 2);
list.add("cantaloupe", 3);
System.out.println("List has "+ list.size() + " nodes.");
list.outputList();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
Your size method contains an infinite loop which explain why the outputs are never reached.
while (position != null)
{
count++;
head = position.getLink();
}
You are looping until position is null, but never assign anything to position and instead assign to head. Instead, you want to do
while (position != null)
{
count++;
position = position.getLink();
}
Now you would get the output
List has 3 nodes.
cantaloupe 3
bananas 2
apples 1