thread "main" java.lang.NullPointerException, Implement three stack in a single array - java

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;
}
}

Related

get kth-largest-element-in-an-array - implemented using maxheap but getting time exceeded in leetcode

I am trying to solve this leetcode challenge . I implemented a MaxHeap and tried to popout the values to get the Kth largest element in the array but I get a time limit exceeded.
Is there any issue with my MaxHeap implementation that it is slow or can this be done in a faster method?
Problem
https://leetcode.com/problems/kth-largest-element-in-an-array/
class Solution {
private int capacity = 10;
private int size = 0;
int items [] = new int[capacity];
//parent = (i-1)/2
//left-child = 2i+1
//right-child = 2i
public int findKthLargest(int[] nums, int k) {
for(int i=0;i<nums.length;i++){
push(nums[i]);
}
//printHeapArray();
for(int i=0; i<k-1; i++){
int val = pop();
System.out.println("max val popped" + val);
// printHeapArray();
}
return peek();
}
private int getLeftChildIndex(int index){
return index*2+1;
}
private int getRightChildIndex(int index) {
return index*2;
}
private int getParentIndex(int index) {
return (index-1)/2;
}
private int leftChild(int index) {
return items[getLeftChildIndex(index)];
}
private int rightChild(int index) {
return items[getRightChildIndex(index)];
}
private int parent(int index) {
return items[getParentIndex(index)];
}
private boolean hasParent(int index){
return getParentIndex(index) >= 0;
}
private boolean hasLeftChild(int index){
return getLeftChildIndex(index) < size;
}
private boolean hasRightChild(int index){
return getRightChildIndex(index) < size;
}
private void swap(int indexOne, int indexTwo) {
int temp = items[indexOne];
items[indexOne] = items[indexTwo];
items[indexTwo] = temp;
}
private void ensureCapacity() {
if(capacity == size -1) {
items = Arrays.copyOf(items, capacity*2);
capacity *= 2;
}
}
public int peek() {
if(size == 0) {
throw new IllegalStateException();
}
return items[0];
}
public void push(int item) {
ensureCapacity();
items[size] = item;
size++;
heapifyUp();
}
private void heapifyUp() {
int index = size - 1;
while(hasParent(index) && parent(index) < items[index]) {
swap(getParentIndex(index), index);
index = getParentIndex(index);
}
}
public int pop() {
if(size == 0 ) throw new IllegalStateException();
int item = items[0];
items[0] = items[size-1];
size--;
heapifyDown();
return item;
}
//1.Compare the children first and find the child you want to compare against with parent
//2.Compare the selected child with its parent to see if it needs to be swapped
private void heapifyDown() {
int index = 0;
while(hasLeftChild(index))
{
int smallerChildIndex = getLeftChildIndex(index);
if(hasRightChild(index) && rightChild(index) > leftChild(index)){
smallerChildIndex = getRightChildIndex(index);
}
if(items[index] > items[smallerChildIndex]) {
break;
}
if(items[smallerChildIndex] > items[index]) {
swap(smallerChildIndex, index);
}
index = smallerChildIndex;
}
}
public void printHeapArray(){
System.out.println(Arrays.toString(items));
}
}
You have an infinite loop, because you're using the wrong formulas for left-child-index and right-child-index.
Look at heapifyDown. The first index tested is 0, and getRightChildIndex() says that it's right child is also at 0*2 == 0.
For heaps with the root at 0, the left and right children of i are at i*2+1 and i*2+2. For heaps with the root at 1 (not your case), the left and right children of i are at i*2 and i*2+1.
Note that if you fix this then your algorithm can work, but it won't be awesome. Appropriate solutions for this problem use quickselect (expected O(n)), a min-heap (O(n * log k)), or a partial heapsort (O(n + k log n)). Yours is like a partial heap sort, but without the O(n) heapify at the start, giving O(n log n).

Im receiving a String index out of range question for a java program i wrote for my assignment

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.

The for each loop for the custom data type (ArrayList) with self implemented iterator does not run

import java.util.Arrays;
import java.util.Iterator;
public class ArrayList<Type> implements Iterable<Type> {
Type[] arr = (Type[]) new Object[10];
int size = 0;
//change capacity
public void newCapacity(int i) {
if (i == 0) {
int newIncreasedCapacity = arr.length * 2;
arr = Arrays.copyOf(arr, newIncreasedCapacity);
} else if (i == 1) {
int newDecreasedCapacity = arr.length / 2;
arr = Arrays.copyOf(arr, newDecreasedCapacity);
}
}
// add an item
public void add(Type item) {
if (size == arr.length) {
newCapacity(0);
}
arr[size++] = item; //increases size after appending
}
//remove an item
public Type remove(int index) {
if (size <= arr.length / 4) {
newCapacity(1);
}
Type removedItem = (Type) arr[index];
for (int i = index; i < size - 1; i++) {
arr[i] = arr[i + 1];
}
size -= 1;
return removedItem;
}
public int size() {
int count = 0;
for (int i = 0; i < size; i++) {
count += 1;
}
return count;
}
#Override
public Iterator<Type> iterator() {
return new ArrayIterator(arr);
}
class ArrayIterator<Type> implements Iterator<Type> {
private Type[] arrayList;
public ArrayIterator(Type[] newArray) {
arrayList = newArray;
}
// check if next element not null
public boolean hasNext() {
return (arrayList[size + 1] != null);
}
// next element
public Type next() {
if (arrayList[size + 1] != null) {
return (arrayList[size + 1]);
} else {
return null;
}
}
}
// Main Method
public static void main(String[] args) {
ArrayList<Integer> new_arr = new ArrayList<>();
new_arr.add(5);
new_arr.add(7);
new_arr.add(9);
new_arr.remove(0);
System.out.println(new_arr.size());
for (int i : new_arr) {
System.out.println(new_arr.size());
System.out.println(i);
}
}
}
I implemented the code for a custom ArrayList and also implemented an iterator for my custom data type, but I am facing an issue.
So when i run the for each loop in the main method, the loop does not run and thus nothing is printed on the console.I have checked the array which is being used for the for-each loop is not empty.Please help!
I think that you should fix your Iterator to something like
class ArrayIterator<Type> implements Iterator<Type> {
private Type[] arrayList;
private int position;
public ArrayIterator(Type[] newArray) {
arrayList = newArray;
position = 0;
}
// check if next element not null
public boolean hasNext() {
return (position != size);
}
// next element
public Type next() {
if (arrayList[position] != null) {
return (arrayList[position++]);
} else {
return null;
}
}
}
You are using the position of the size of the array to calculate the next() and hasNext(), the hasNext() is always returning null.

displaying circular queue in java

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();
}
}
}

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