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.
Related
I would like to apologise in advance if im doing something wrong with the code formatting because this is my second time posting here
I have a java assignment due in a couple of days in which the user enters a string and only the integers are collected from it and placed in the array intArray
Now i think i got the logic right in the code below but when i run it in the main, it asks for the string and the boolean, when i enter both it gives me the error
"Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 115"
This is what i entered for example
"Enter a string and true if you want to skip errors or false if you want to skip errors
sdak23
false"
this is my main:
import java.util.Scanner;
public class MainStringToIntArray {
public static void main(String[] args) {
Scanner intut = new Scanner(System.in);
Scanner input = new Scanner(System.in);
StringToIntArray s1 = new StringToIntArray();
System.out.println("Enter a string and true if you want to skip errors or false if you want to skip errors");
s1.scanStringToIntArray(intut.next(), input.nextBoolean());
}
}
import java.util.Arrays;
import java.util.Scanner;
public class StringToIntArray {
private int[] intArray = new int[10];
public StringToIntArray() {
Arrays.fill(intArray, Integer.MIN_VALUE);
}
public int indexOf(int intToFind) {
int b = 0;
for (int a = 0; a < intArray.length; a++) {
if (intArray[a] == intToFind) {
b = intArray[a];
}
else {
b = -1;
}
}
return b;
}
public int indexOf(String intToFind) {
int b = 0;
for (int a = 0; a < intArray.length; a++) {
if (intArray[a] == Integer.parseInt(intToFind)) {
b = intArray[a];
}
else {
b = -1;
}
}
return b;
}
public boolean contains(int intToFind) {
int a = indexOf(intToFind);
if (a > 0) {
return true;
}
else {
return false;
}
}
public boolean contains(String intToFind) {
int a = indexOf(intToFind);
if (a > 0) {
return true;
}
else {
return false;
}
}
public int get(int index) {
if(index < 0 && index > 10) {
return Integer.MIN_VALUE;
}
else {
return intArray[index];
}
}
public boolean scanStringToIntArray(String s, Boolean skipErrors) {
Boolean result = null;
Scanner input = new Scanner(s);
int l = s.length();
if ((skipErrors)) {
String discard = null;
for (int a = 0; a < l; a++) {
for (int z = 0; z < l; z++) {
if (input.hasNextInt(s.charAt(z))) {
intArray[a] = s.charAt(z);
System.out.println(a);
result = true;
}
else {
discard = discard + s.charAt(z);
}
}
}
}
else {
for (int v = 0; v < l; v++) {
for (int p = 0; p < l; p++) {
if ((input.hasNextInt(s.charAt(p)))) {
intArray[v] = s.charAt(p);
System.out.println(v);
}
else {
System.out.println(v);
result = false;
}
}
}
}
return result;
}
}
The issue is in the get method. It is logically impossible for the index to be both less than 0 and greater than 10; you probably want to use the logical or operator (||). Also, the maximum index of the array is actually 9, as arrays are zero indexed.
public int get(int index) {
if(index < 0 || index > 9) {
return Integer.MIN_VALUE;
}
else {
return intArray[index];
}
}
There are other logical errors in your code as well. All your indexOf methods should be returning the index where the element was first found instead of the element itself and your else branch is always resetting it to -1 each time it is not found.
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);
}
}
I have the following code where I have implemented a circular array. The problem comes when I try to display it. The display method works well until the array gets full and last goes back to 0. Therefore last and first are both 0 and the for loop doesn't execute.
public class PassengerQueue
{
private Passenger[] queueArray = new Passenger[TrainStation.WAITING_ROOM_CAPACITY];
private int first = 0;
private int last = 0;
private int maxStayInQueue = 0; //number of seconds that the passenger who stayed longest in the queue
private int maxLength = 0; //the maximum legth that was reached by the queue
private int currentSize = 0;
public void add(Passenger next)
{
//if the queue is not full - check for the circular queue
if (isFull()){
System.out.println("The queue is full");
}
else
{
queueArray[last] = next;
last = (last + 1) % queueArray.length;
currentSize++;
maxLength++;
}
}
public Passenger remove()
{
Passenger removedPassenger = null;
//if the queue array is not empty
//remove passenger
if (isEmpty())
{
System.out.println("The queue is empty");
}
else
{
removedPassenger = queueArray[first];
queueArray[first] = null;
first = (first + 1) % queueArray.length;
currentSize--;
}
return removedPassenger;
}
public Boolean isEmpty()
{
return (currentSize == 0);
}
public Boolean isFull()
{
return (currentSize == queueArray.length);
}
public void display()
{
if (isEmpty())
{
System.out.println("The queue is empty");
}
else
{
for(int i = first; i < last; i++)
{
queueArray[i].display();
}
}
}
Any help would be appreciated! Thank You
You can change the loop so it iterates from 0 to size. This also fixes the problem where last is less than first because items have been removed.
for(int i = 0; i < currentSize; i++)
{
queueArray[(first + i) % queueArray.length].display();
}
Just use the properties on the array itself to display:
public void display()
{
if (isEmpty())
{
System.out.println("The queue is empty");
}
else
{
for(int i = 0; i < queueArray.length; i++)
{
queueArray[i].display();
}
}
}
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())
The purpose of this code is to implement three stacks in a single array. I use linked node to implement stack. the elements are pushed into array one by one directly, and the elements in each stack are connected by previous pointer. the pointer is int value corresponding to index in array where the item is stored. nextAvaIndexmethod return next available index that can store new pushed item. Because there will space released in the beginning of the array after executing pop method. ifindexused < arr.lengthit will keep moving forward to store new item, while if indexusedreaches end of array, the method will search is there free space in beginning of array.
But when I run it, it throws NullPointerException, i know the meaning of this error, but I can't fix it. Thanks for your comments! Is the code correct? One more question of removal an item from int type array. I letarr[i].data = 0 to delete the item, and use statement arr[i].data == 0 to check if one space is null. But what if one space store0? Thanks for your suggestion!
public class FlexiblemultiStack {
private int[] toppoint = {-1, -1, -1};// assume number of stack ==3;
private int indexused = 0;
private stackNode[] arr;
public FlexiblemultiStack(int sizeEach, int stackNO) {
arr = new stackNode[sizeEach * stackNO]; //
}
public boolean isEmpty(int stackNum) {
return toppoint[stackNum] == 0;
}
public void push(int item, int stackNum) {
int lastIndex = toppoint[stackNum];
int nextIndex = nextAvaIndex();
if (nextIndex == -1) { // if nextIndex = -1, there is no more space!
System.out.println("There is no more space!");
} else {
toppoint[stackNum] = nextIndex;
arr[toppoint[stackNum]] = new stackNode(item, lastIndex);
indexused++;
}
}
public int pop(int stackNum) {
if (toppoint[stackNum] == -1) {
return 0;
} else {
int value = arr[toppoint[stackNum]].data;
int lastIndex = toppoint[stackNum];
toppoint[stackNum] = arr[toppoint[stackNum]].previous;
arr[lastIndex] = null;
indexused--;
return value;
}
}
public int peek(int stackNum) {
return arr[toppoint[stackNum]].data;
}
public int nextAvaIndex() {
int index = -1;
if (indexused == arr.length || arr[indexused].data != 0) {
for (int i = 0; i < arr.length; i++) {
if (arr[i].data == 0) { // error
index = i;
break;
}
}
return index;
} else {
return indexused;
}
}
public void print(int stackNum) {
while (toppoint[stackNum] != -1) {
System.out.print(arr[toppoint[stackNum]].data + "<--");
toppoint[stackNum] = arr[toppoint[stackNum]].previous;
}
}
public void printarr(){
for(int i = 0; i< arr.length;i++){
System.out.print(arr[i]);
}
}
public class stackNode { // Exception in thread "main" java.lang.NullPointerException
List item
private int previous;
private int data;
public stackNode(int StackSize) {
this.previous = -1;
}
public stackNode(int value, int prev) {
data = value;
previous = prev;
}
}
}
Exception in thread "main" java.lang.NullPointerException
at stackandqueue.FlexiblemultiStack$stackNode.access$000(FlexiblemultiStack.java:86)
at stackandqueue.FlexiblemultiStack.nextAvaIndex(FlexiblemultiStack.java:61)
at stackandqueue.FlexiblemultiStack.push(FlexiblemultiStack.java:32)
at stackandqueue.StackandQueue.main(StackandQueue.java:71)
/Users/xchen011/Library/Caches/NetBeans/8.1/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
In the pop() method, it appears you are denoting an open index by setting the array index to null (arr[lastIndex] = null). In nextAvaIndex() you check if the index is available by examining arr[i].data. If arr[i] has been set to null by pop(), you will get the NullPointerException. To make the definition of available consistent with the check for availability, try replacing arr[indexused].data != 0 with arr[indexused] != null and if(arr[i].data == 0) with if(arr[i] == null) in the nextAvaIndex() method.
public int nextAvaIndex() {
int index = -1;
if (indexused == arr.length || arr[indexused] != null) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == null) { // error
index = i;
break;
}
}
return index;
} else {
return indexused;
}
}