Counting nodes for each index + toString - java

So I was wondering if there is a way to print out which index of the list has the most collisions? As well as this, I wanted to know, what is the best way to produce a toString() for my LinkedList? I've tried a few times with the default implementation for a LinkedList toString but I can't quite figure out how to do it.
Thanks in advance!
Code:
static LinkedList<Node> hashTable[] = new LinkedList[100];
static class Node {
int value;
int key;
#Override
public String toString() {
return "Value: " + value + " " + "Key: " + key;
}
}
public static void main(String[] args) throws FileNotFoundException {
File f = new File("Ex5.txt");
Scanner scan = new Scanner(f);
if (f.exists() == false) {
System.out.println("File doesn't exist or could not be found.");
System.exit(0);
}
for (int i = 0; i < 100; i++) {
hashTable[i] = null;
}
while (scan.hasNextInt()) {
int n = scan.nextInt();
insert(n, hashFunction(n));
}
for (int i = 0; i < 100; i++) {
System.out.println(hashTable[i]);
}
int emptyEntries = 0;
for (int i = 0; i < 100; i++) {
if (hashTable[i] == null) {
emptyEntries += 1;
}
}
System.out.println("Number of empty entries: " + emptyEntries);
}
public static void insert(int key, int value) {
int index = hashFunction(value);
LinkedList<Node> items = hashTable[index];
if (items == null) {
items = new LinkedList<>();
Node item = new Node();
item.key = key;
item.value = value;
items.add(item);
hashTable[index] = items;
} else {
for (Node item : items) {
if (item.key == key) {
item.value = value;
return;
}
}
Node item = new Node();
item.key = key;
item.value = value;
items.add(item);
}
}
public static int hashFunction(int value) {
int hashKey = value % 100;
return hashKey;
}

Classes are objects. LinkedList is a class. All objects extend java.lang.Object and you can always call Object.toString() on them, but what you are likely looking for is a way to print out all the values. In this case, it is best to use a for loop:
for(int i=0; i<items.size(); i++){
System.out.println(items.get(i));
}
You are printing multiple lines, each containing various amounts of Node objects. You want to find which line has the most amounts of Node objects.
The way to do this is simple. You need nested for loops to print that, and thus you can do this, with your for loops
int maxNodes = Integer.MIN_VALUE;
int index = -1;
for(int i=0; i<LinkedList.size(); i++){
int nodes = 0;
for(int j=0; j<nestedLinkedList.size(); j++){
System.out.print(NodeInformation);
nodes++;
}
if(nodes>maxNodes){
index = i;
maxNodes = nodes;
}
System.out.println();
}
This sample code would find which line would contain the most Node objects.

Related

Trying to find smallest weight of widest path of a graph using modified Dijkstra's Algorithm in Java

I need to give the widest path from one chosen node to another in a self-generated graph. After this, I need to state the "bottleneck" or smallest weight on the computed path. As it is, I don't know where to start to find the bottleneck and I'm having trouble showing the path. Under the Graph class, in the printPath method, I am currently getting a StackOverflow Error from presumably infinite recursion, though I don't understand how its recurring infinitely in the first place. I've used some code from here: https://www.geeksforgeeks.org/printing-paths-dijkstras-shortest-path-algorithm/ with slight modification to find the largest path rather than the shortest as well renaming variables. I feel an error in said modification is most likely one source of the problem. Following is the output of my most recent test:
Enter a positive integer.
5
Node list: {1,2,3,4,5}
Edge list: {(2,3,17),(2,4,8),(3,5,3)}
Enter a source node.
1
Enter a destination node
5
Vertex: 1 --> 5
Distance: 20
Path: Exception in thread "main" java.lang.StackOverflowError
at Graph.printPath(Graph.java:104)
at Graph.printPath(Graph.java:104)
at Graph.printPath(Graph.java:104)
Here's my code so far. I've had my code in separate classes, so I apologize for any errors I may have made combining them to one file. I also apologize for the massive and messy block of code but I don't think there's anything here I can weed out before posting.
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Random;
public class Graph{
private ArrayList<Node> nodes = new ArrayList<Node>();
private ArrayList<Edge> edges = new ArrayList<Edge>();
private int[][] adjMatrix;
Graph(int numNodes, int weightBound, double probability){
ArrayList<Node> tempNodeList = new ArrayList<Node>(numNodes);
for(int i = 0; i < numNodes; i++) {
Node tempNode = new Node(i+1);
tempNodeList.add(tempNode);
}
this.nodes = tempNodeList;
Random rand = new Random();
for(int i = 0; i < numNodes; i++) {
for(int j = i+1; j < numNodes; j++) {
if(rand.nextInt((int)Math.round(1/probability)) == 0) {
Edge tempEdge = new Edge(rand.nextInt(5*numNodes-1)+1, nodes.get(i), nodes.get(j));
edges.add(tempEdge);
}
}
}
adjMatrix = new int[numNodes][numNodes];
for(int i = 0; i < edges.size(); i++) {
adjMatrix[edges.get(i).getNode(0).getID()-1][edges.get(i).getNode(1).getID()-1] = edges.get(i).getWeight();
adjMatrix[edges.get(i).getNode(1).getID()-1][edges.get(i).getNode(0).getID()-1] = edges.get(i).getWeight();
}
}
public void printGraph() {
System.out.print("Node list: {");
for(int i = 0; i < nodes.size(); i++) {
nodes.get(i).printNode();
if(i != nodes.size()-1) {
System.out.print(",");
}
}
System.out.println("}");
System.out.print("Edge list: {");
for(int i = 0; i < edges.size(); i++) {
edges.get(i).printEdge();
if(i != edges.size()-1) {
System.out.print(",");
}
}
System.out.println("}");
}
public void widestPath(int source, int dest){
int numVertices = adjMatrix[0].length;
int[] longestDists = new int[numVertices];
boolean[] inPath = new boolean[numVertices];
for(int i = 0; i < numVertices; i++) {
inPath[i] = false;
}
longestDists[source] = 0;
Node tempNode = nodes.get(source);
tempNode.setParent(-1);
nodes.set(source, tempNode);
for(int i = 1; i < numVertices; i++) {
int furthestNode = -1;
int longestDist = Integer.MIN_VALUE;
for(int index = 0; index < numVertices; index++) {
if(!inPath[index] && longestDists[index] > longestDist) {
furthestNode = index;
longestDist = longestDists[index];
}
}
inPath[furthestNode] = true;
for(int index = 0; index < numVertices; index++) {
int edgeWeight = adjMatrix[furthestNode][index];
if(edgeWeight > 0 && ((longestDist + edgeWeight) > (longestDists[index]))){
tempNode = nodes.get(index);
tempNode.setParent(furthestNode);
nodes.set(index, tempNode);
longestDists[index] = longestDist + edgeWeight;
}
}
}
printResult(source, longestDists, dest);
}
public void printResult(int source, int[] dists, int dest) {
System.out.println("Vertex: " + (source+1) + " --> " + (dest+1));
System.out.println("Distance: " + dists[dest]);
System.out.print("Path: ");
printPath(dest);
}
public void printPath(int dest) {
if(nodes.get(dest).getParent() == -1) {
return;
}
printPath(nodes.get(dest).getParent()); // StackOverflow here
System.out.print((dest+1) + " ");
}
}
public class Node {
private int ID;
private int distance = Integer.MIN_VALUE;
private int parent;
Node(int id){
this.ID = id;
}
public int getID() {
return this.ID;
}
public void printNode() {
System.out.print(this.ID);
}
public void setDist(int dist) {
this.distance = dist;
}
public int getDist() {
return this.distance;
}
public void setParent(int p) {
this.parent = p;
}
public int getParent() {
return this.parent;
}
}
public class Edge {
private int weight;
private ArrayList<Node> vertices = new ArrayList<Node>(2);
Edge(int weight){
this.weight = weight;
}
Edge(int weight, Node n1, Node n2){
this.weight = weight;
this.vertices.add(n1);
this.vertices.add(n2);
}
public int getWeight() {
return weight;
}
public void setNodes(Node n1, Node n2) {
this.vertices.set(0, n1);
this.vertices.set(1, n2);
}
public ArrayList<Node> getNodes(){
return vertices;
}
public void printEdge() {
System.out.print("(" + vertices.get(0).getID() + "," + vertices.get(1).getID() + "," + this.weight + ")");
}
public int otherNodeIndex(int ID) {
if(vertices.get(0).getID() == ID) {
return 1;
}else if(vertices.get(1).getID() == ID) {
return 0;
} else {
return -1;
}
}
public Node getNode(int index) {
return vertices.get(index);
}
}
public class Driver {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int input = -1;
while(input <= 0) {
System.out.println("Enter a positive integer.");
input = sc.nextInt();
}
double probability = 0.25;
Graph gr = new Graph(input, input*5, probability);
gr.printGraph();
int source = -1;
int dest = -1;
while(source < 0 || source > input) {
System.out.println("Enter a source node.");
source = sc.nextInt()-1;
}
while(dest < 0 || dest > input) {
System.out.println("Enter a destination node");
dest = sc.nextInt()-1;
}
gr.widestPath(source, dest);
}
}

Java assignment to use Dijkstras search method, breath-first and depth first

Hello StackOverflow community, need your help. I have a final for my java class and its asking for:
Generate a graph with 100,000 nodes, where each node randomly has between 1 and 5 connections to other nodes. Each node should contain within it a random value between 1 and 300,000. (So generally about 1 in 3 searches will yield a query match). Allow the user to enter a number to search for, and implement each of the following three types of searching algorithms. Breadth-First. (30 points) Depth-First. (30 points) Dijkstra's Algorithm. (40 points)
Do not allow back-tracking in your searches. (Mark nodes that you already searched as complete, and do not re-visit them in the same search). Each search should return the following: The Success/Failure of your search. The length of the shortest path to the found node. The total number of nodes examined during the search. Optionally you may return the exhaustive display of the shortest path, for testing and verification.
For some reason, my IDE shows that BFS and Dijkstras has "duplicated code fragment 17 lines long" can someone look at tell me how to fix it or maybe a better way to implement it? Also, if i try to do nodesNum > 30k in "Driver Class" i get a memory leak.
Here is the code:
Class Graph:
import java.util.*;
import javax.swing.JOptionPane;
class Graph
{
private Listing[] vertex;
private int[][] edge;
private int max;
private int numberOfVertices;
private int nodeCheck = 0;
private int selectNum = 0;
Graph(int g)
{
vertex = new Listing[g];
edge = new int[g][g];
max = g;
numberOfVertices = 0;
}
private void depthFirstSearch(int firstVertex)
{
int v;
Stack<Integer> nodeStack = new Stack<>();
for(int i = 0; i<numberOfVertices; i++)
{
if (vertex[i] != null) {
vertex[i].setPushed(false);
}
}
nodeStack.push(firstVertex);
vertex[firstVertex].setPushed(true);
while (!nodeStack.empty())
{
v = nodeStack.pop();
vertex[v].visit();
nodeCheck++;
for (int column = 0; column < numberOfVertices; column++)
{
if(edge[v][column] == 1 && vertex[column].getPushed())
{
nodeStack.push(column);
vertex[column].setPushed(true);
}
}
}
}
private void breathFirstSearch(int firstVertex)
{
int V;
Queue<Integer> nodeQueue = new LinkedList<>();
for(int i = 0; i < numberOfVertices; i++)
{
if(vertex[i] != null)
vertex[i].setPushed(false);
}
nodeQueue.add(firstVertex);
vertex[firstVertex].setPushed(true);
while(!nodeQueue.isEmpty())
{
V = nodeQueue.remove();
vertex[V].visit();
nodeCheck++;
for(int column = 0; column < numberOfVertices; column++)
{
if(edge[V][column] == 1 && vertex[column].getPushed())
{
nodeQueue.add(column);
vertex[column].setPushed(true);
}
}
}
}
private void Dijkstra(int firstVertex)
{
int v;
LinkedList<Integer> nodeQueue = new LinkedList<>();
int i = 0;
while (i < numberOfVertices)
{
if(vertex[i] != null)
vertex[i].setPushed(false);
i++;
}
nodeQueue.add(firstVertex);
vertex[firstVertex].setPushed(true);
while(!nodeQueue.isEmpty())
{
v = nodeQueue.remove();
vertex[v].visit();
nodeCheck++;
for(int column = 0; column < numberOfVertices; column++)
{
if(edge[v][column] == 1 && vertex[column].getPushed())
{
nodeQueue.add(column);
vertex[column].setPushed(true);
}
}
}
}
private void insertVertex(int vertexNumber, Listing newListing)
{
if(vertexNumber >= max)
{
return;
}
vertex[vertexNumber] = newListing.deepCopy();
numberOfVertices++;
}
private void insertEdge(int fromVertex, int toVertex)
{
if(vertex[fromVertex] == null || vertex[toVertex] == null)
return;
edge[fromVertex][toVertex] = 1;
}
void showVertex(int vertexNumber)
{
System.out.print(vertex[vertexNumber]);
}
void showEdges(int vertexNumber)
{
for(int column = 0; column < numberOfVertices; column++)
{
if(edge[vertexNumber][column] == 1)
{
System.out.println(vertexNumber + "," + column);
}
}
System.out.println();
}
void InitializeNodes(Graph G, int nodesNum)
{
Random random = new Random();
for (int i = 0; i < nodesNum; i++ )
{
Listing v = new Listing(random.nextInt(300000) + 1);
G.insertVertex(i, v);
}
int vertexListNumber = G.vertex.length;
List<Integer> list = new ArrayList<>();
for (int i = 0; i < nodesNum; i++ )
{
list.add(i);
}
Collections.shuffle(list);
for (int i = 0; i < vertexListNumber; i++ )
{
int randnum = random.nextInt(5);
for (int j = 0; j < randnum; j++ )
{
int rand = random.nextInt(5);
G.insertEdge(i, list.get(rand));
}
}
}
int Search()
{
String search = JOptionPane.showInputDialog("Enter Node to search:");
try
{
if(search != null)
{
selectNum = Integer.parseInt(search);
}
}
catch (NumberFormatException e)
{
selectNum = 0;
}
return selectNum;
}
private int SelectPane()
{
String paneSelect = JOptionPane.showInputDialog("Choose a search method:" +
"\n\t1: Use Depth-First Search" +
"\n\t2: Use Breadth-First Search" +
"\n\t3: Use Dijkstra's Search" +
"\n\t4: Close Program");
int selectNum = 0;
try{
if(paneSelect != null)
{
selectNum = Integer.parseInt(paneSelect);
}
}
catch (NumberFormatException ignored)
{
}
return selectNum;
}
void algorithmChoice(Graph graph, int vertexStart)
{
int paneNum = 0;
while (paneNum != 4)
{
paneNum = SelectPane();
switch (paneNum)
{
case 1:
graph.depthFirstSearch(vertexStart);
System.out.println("Nodes counted were: " + nodeCheck);
System.out.println("------------------------------------");
break;
case 2:
graph.breathFirstSearch(vertexStart);
System.out.println("Nodes counted were: " + nodeCheck);
System.out.println("------------------------------------");
break;
case 3:
graph.Dijkstra(vertexStart);
System.out.println("Nodes counted were: " + nodeCheck);
System.out.println("------------------------------------");
break;
case 4:
break;
default:
JOptionPane.showMessageDialog(null, "Enter 4 to quit.");
break;
}
}
}
}
Class Listing:
public class Listing
{
private int value;
private boolean pushed;
Listing(int v)
{
value = v;
}
public String toString()
{
return ("Vertex: " + value + "\n" );
}
Listing deepCopy()
{
return new Listing(value);
}
boolean getPushed()
{
return !pushed;
}
void setPushed(boolean value)
{
pushed = value;
}
void visit()
{
System.out.println(this);
}
}
Class Driver:
public class Driver
{
public static void main(String[] args)
{
int nodesNum = 30000; //Can go up to 30k nodes, otherwise causes memory leak.
Graph graph = new Graph(nodesNum);
graph.InitializeNodes(graph, nodesNum);
for(int i = 0; i<5; i++)
{
System.out.print("Node " + i + "\'s ");
graph.showVertex(i);
System.out.print("Its routes are:\n");
graph.showEdges(i);
}
int select = graph.Search();
graph.algorithmChoice(graph, select);
}
}
Thanks alot for your help!
The error you get is due to exceeding max heap size when creating a edge = new int[g][g]; where g can be as high as 100,000 in your case.
I would suggest avoiding the use of such huge matrix.
Instead introduce an Edge object :
class Edge{
private final int fromVertex, toVertex;
Edge(int fromVertex, int toVertex){
this.fromVertex = fromVertex;
this.toVertex = toVertex;
}
#Override
public boolean equals(Object obj) {
if( ! (obj instanceof Edge)) return false;
Edge other = (Edge)obj;
return connects(other.fromVertex, other.toVertex);
}
boolean connects(int fromVertex, int toVertex){
return fromVertex == this.fromVertex && toVertex == this.toVertex ||
fromVertex == this.toVertex && toVertex == this.fromVertex;
}
}
and use it in Graph.
Instead of private int[][] edge; use a collection of Edges:
private final Set<Edge> edges = new HashSet<>();
Change insertEdge to:
private void insertEdge(int fromVertex, int toVertex)
{
if(vertex[fromVertex] == null || vertex[toVertex] == null)
return;
edges.add(new Edge(fromVertex, toVertex));
}
and add a method to check if there is an edge between two vertices:
private boolean isEdgeBetween(int fromVertex, int toVertex)
{
for(Edge edge : edges){
if(edge.connects(fromVertex, toVertex)) return true;
}
return false;
}
Usage : if( isEdgeBetween(v,column) && vertex[column].getPushed())
instead of: if(edge[v][column] == 1 && vertex[column].getPushed())

Improve the speed of the program to O(n), log(n) or possibly O(1)

Is there a way to improve the speed of this program? I was thinking recursion, but with the test cases it might crash the program with an overflow on the stack.
class BetterUF extends UF {
public BetterUF(int size) {
super(size);
}
// Determine if nodes are in different trees
public boolean inSameSet(int a, int b) {
Integer root1 = find(a); // Find root of node a
Integer root2 = find(b); // Find root of node b
return root1.intValue() == root2.intValue(); // Compare roots
}
// Merge two subtrees
public void union(int a, int b) {
Integer root1 = find(a); // Find root of node a
Integer root2 = find(b); // Find root of node b
if (root1.intValue() != root2.intValue())
array[root2] = root1; // Merge
}
// return the root of curr's tree
public Integer find(Integer curr) {
if (array[curr] == -1)
return curr; // At root
while (array[curr] != -1)
curr = array[curr];
return curr;
}
}
abstract class UF {
protected Integer [] array; // Node array
public UF(int size) {
array = new Integer[size]; // Create node array
for (int i=0; i<size; i++)
array[i] = new Integer(-1); // Initially every node is a root
}
/** Determine if nodes are in different trees */
public abstract boolean inSameSet(int a, int b);
/** Merge two subtrees */
public abstract void union(int a, int b);
/** #return The root of curr's tree */
public abstract Integer find(Integer curr);
// Use to print the disjoint sets
String printUFSets() {
StringBuffer out = new StringBuffer(1000);
out.append("{ ");
for (int i = 0; i < array.length; i++) {
boolean left_brace_printed = false;
// Anything that has i as its representative will be printed
for (int j = 0; j < array.length; j++) {
int k = find(j);
if (k == i && !left_brace_printed) {
out.append(" { " + j + " ");
left_brace_printed = true;
}
else if (k == i)
out.append(" " + j + " ");
}
if (left_brace_printed)
out.append("} ") ;
}
out.append(" }") ;
return out.toString();
}
// Use to print the parent pointers
String printUFTrees() {
StringBuffer out = new StringBuffer(1000);
for (int i=0; i<array.length; i++) {
out.append(array[i] + " ");
}
return out.toString();
}
// Return the average number of nodes on a path in the tree
float avgNodesOnPath () {
return 0.0f;
}
}
What do you guys think to speed this up?

Printing a Linked List in Java

I'm working on an assignment where I need to create a Linked List given a template. However, up until this point, I've been stumped on how to print out the linked list. Can anyone figure out what am I doing wrong?
Edit:
Sorry, I should point out that I'm getting a java.lang.NullPointerException error on line 27 of NumberList when I compile.
error when I compile.
NumberList.java
import java.util.*;
public class NumberList {
private Node head;
public NumberList() {
}
public void insertAtHead(int x) {
Node newNode = new Node(x);
if (head == null)
head = newNode;
else {
newNode.setNext(head);
head = newNode;
}
}
public void insertAtTail(int x) {
}
public void insertInOrder(int x) {
}
public String toString() {
Node tmp = head;
String result = "";
while (tmp.getNext() != null) {
result += tmp.toString() + " ";
}
return result;
}
//---------------------
// test methods
//---------------------
public static void testInsertAtHead() {
Random r = new Random();
int n = 20;
int range = 1000;
NumberList list = new NumberList();
for (int i=1; i<=n; i++) {
int x = r.nextInt(range);
list.insertAtHead(x);
System.out.println("" + x + ": " + list);
}
}
public static void testInsertAtTail() {
Random r = new Random();
int n = 20;
int range = 1000;
NumberList list = new NumberList();
for (int i=1; i<=n; i++) {
int x = r.nextInt(range);
list.insertAtTail(x);
System.out.println("" + x + ": " + list);
}
}
public static void testInsertInOrder() {
Random r = new Random();
int n = 20;
int range = 1000;
NumberList list = new NumberList();
for (int i=1; i<=n; i++) {
int x = r.nextInt(range);
list.insertInOrder(x);
System.out.println("" + x + ": " + list);
}
}
public static void main(String[] args) {
//testInsertAtHead();
//testInsertAtTail();
testInsertInOrder();
}
}
Node.java
class Node {
private int number;
private Node next;
public Node(int n) {
this.number = n;
this.next = null;
}
public Node getNext() {
return next;
}
public int getNumber() {
return number;
}
public void setNext(Node n) {
if (n == null)
return;
n.setNext(next);
next = n;
}
public String toString() {
return number + "";
}
}
Your problem is:
while (tmp.getNext() != null) {
result += tmp.toString() + " ";
}
You are not advancing to the next link in your list at all. You should consider performing
tmp = tmp.getNext(). But before doing so make sure your while condition is
while (tmp != null) to avoid a NullPointerException.
And the NullPointerException you are getting in line 27 (which we can't know where it is) is probably because head isn't initialized since you call insertInOrder before insertAtHead, which is the only place where head is initialized in your program.
You're calling insertAtTail and insertInOrder methods, but they are empty. As well as your NumberList constructor.

Java code freezing mid execution

Im running my code, and after it says the first print statement it pauses. It pauses at a point where it calls a function "insert" and simply doesnt respond anything. it prints "adding dog, cat, & horse" but then just stops, doesnt do anything after that.
main function
package assignment2;
public class Main {
public static void main(String[] args) {
OrderedStringList myList = new OrderedStringList(5);
System.out.println("adding dog, cat, & horse");
myList.Insert("dog");
myList.Insert("cat");
myList.Insert("horse");
myList.Display();
System.out.println("Value pig find = "+ myList.Find("pig"));
System.out.println("Value horse find = "+ myList.Find("horse"));
System.out.println("Adding mouse & rat");
myList.Insert("mouse");
myList.Insert("rat");
myList.Display();
System.out.println("myList size: "+ myList.Size());
if (!myList.Insert("chinchilla"))
System.out.println("Could not add chinchilla, full");
System.out.println("Removing dog, adding chinchilla.");
myList.Delete("dog");
myList.Insert("chinchilla");
myList.Display();
}
}
here is my code of functions
package assignment2;
public class OrderedStringList {
int length;
int numUsed;
String[] storage;
boolean ordered;
public OrderedStringList(int size){
length = size;
storage = new String[length];
numUsed = 0;
}
public boolean Insert(String value){
boolean result = false;
int index = 0;
if (numUsed < length) {
while (index < numUsed) {
int compare = storage[index].compareTo(value);
if (compare < 0)
index++;
}
moveItemsDown(index);
storage[index] = value;
numUsed++;
result = true;
}
return result;
}
private void moveItemsDown(int start){
int index;
for (index = numUsed-1; index >=start; index--){
storage[index+1] = storage[index];
}
}
private void moveItemsUp(int start){
int index;
for (index = start; index < numUsed-1; index++){
storage[index] = storage[index+1];
}
}
public boolean Find(String value){
return (FindIndex(value) >= 0);
}
private int FindIndex(String value) {
int result = -1;
int index = 0;
boolean found = false;
while ((index < numUsed) && (!found)) {
found = (value.equals(storage[index]));
if (!found)
index++;
}
if (found)
result = index;
return result;
}
public boolean Delete(String value){
boolean result = false;
int location;
location = FindIndex(value);
if (location >= 0) {
moveItemsUp(location);
numUsed--;
result = true;
}
return result;
}
public void Display() {
int index;
System.out.println("list Contents: ");
for (index = 0; index < numUsed; index++) {
System.out.println(index+" "+storage[index]);
}
System.out.println("-------------");
System.out.println();
}
public void DisplayNoLF() {
int index;
System.out.println("list Contents: ");
for (index = 0; index < numUsed; index++) {
System.out.print(storage[index]+" ");
}
System.out.println("-------------");
System.out.println();
}
public int Size(){
return numUsed;
}
}
You're getting caught in an infinite loop in the while statement of your Insert function. Consider this piece of code:
while (index < numUsed) {
int compare = storage[index].compareTo(value);
if (compare < 0)
index++;
}
What happens if compare >= 0 for index = 0? Index doesn't increment upwards, then the while loop is called again on index = 0, ad infinitum. You need to increment index outside of the if statement and put a different condition in your if statement.
while (index < numUsed && storage[index].compareTo(value) < 0) {
index++;
}
solved my problem by doing this. i simply removed the for loop and added an extra requirement on the while loop.

Categories