Stack implementation array index out of bound error - java

I have created a stack .
public class STK {
static int capacity = 0;
STK(int size) {
capacity = size;
}
int stackk[] = new int[capacity];
int top = 0;
public void push(int d) {
if(top < capacity) {
stackk[top] = d;
top++;
} else {
System.out.println("Overflow");
}
}
}
its implementation
public class BasicStackImplementation {
public static void main(String[] args) {
STK mystack = new STK(5);
mystack.push(51);
mystack.push(23);
}
}
when i try to run this code it gives an error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at STK.push(STK.java:21)
at BasicStackImplementation.main(BasicStackImplementation.java:6)

Field initializers run before the constructor. Your code is equivalent to this:
static int capacity = 0;
int stackk[]=new int[capacity];
STK(int size)
{
capacity=size;
}
So you're initializing an empty array. To fix it, just initialize stackk inside the constructor:
int[] stackk;
STK(int size)
{
capacity = size;
stackk = new int[capacity];
}
Also, capacity varies by instance and shouldn't be static.

When you made your class, you initialized your array property in your class to equal capacity which is 0. So your array is initialized with 0 elements.
When you call your constructor and set the capacity value, you need to re-initialize your class array equal to new int[value]

Related

Why am I getting a NullPointerException with this ArrayList? [duplicate]

This question already has answers here:
java "void" and "non void" constructor
(5 answers)
Closed 5 years ago.
When ever I add an object to this ArrayList, my resize method, gives me a NullPointerException. The list is initialized with a size of 1, and the first element is added to possition 0 in the array.
Here is my arrayList AKA DynamicArray
//Implementation of a dynamic array
// Add remove methods
public class DynamicArray {
private Object[] data;
private int size;
public void DynamicArray(){
data = new Object[1];
size = 0;
}
public int size(){return size;}
public Object get(int index){return data[index];};
private void resizeIfFull()
{
if (size < data.length){
return;
} else {
Object[] bigger = new Object[2 * data.length];
for (int i = 0; i < data.length; i++){
bigger[i] = data[i];
data = bigger;
}
}
}
public void add(Object obj){
resizeIfFull();
data[size] = obj;
size++;
}
public void add(int index, Object obj){
resizeIfFull();
for(int i = size - 1; i >= index; i--){
data[i+1] = data[i];
}
data[index] = obj;
size++;
}
public void remove(int index){
for(int i = index; i < size; i++){
data[i] = data[i+1];
}
size--;
}
}
Here is my testing class.
public class AlgorTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
DynamicArray dynam = new DynamicArray();
System.out.println(dynam.size());
dynam.add("first");
}
}
Here is my output from the testing class.
0
Exception in thread "main" java.lang.NullPointerException
at DynamicArray.resizeIfFull(DynamicArray.java:20)
at DynamicArray.add(DynamicArray.java:38)
at AlgorTest.main(AlgorTest.java:8)
Confusingly, this isn't a constructor:
public void DynamicArray(){
data = new Object[1];
size = 0;
}
It's a function called DynamicArray (very confusing, I know).
Without the class having a constructor, data remains null and leads to an NPE when you try to access the array.
Drop the void keyword to turn the function into a constructor (which would then initialize data etc):
public DynamicArray(){
data = new Object[1];
size = 0;
}
constructor doesn't have return value , remove return type from constructor (void)
public DynamicArray(){
data = new Object[1];
size = 0;
}
in your case when you initialize object from DynamicArray class then default constructor will execute which does nothing

Does assigning an object to another mean that instant variables will aslo change?

I am trying to to create a stacks which has the following API:
Stacks(int n)// creates stacks of size n
pop() //returns the last element pushed in the stacks
pop(int n) //returns an array of of n elements
push(int e) //appends an element to the stacks
push(int n, ar[]) //appends an array to the stack
The stacks should be able to dynamically change size when needed, so client programs dont have to do it every time.
I have done all that only my problem is when assigning object A to object B doesn't that mean that A will now points to the address of B?
Here is my code and i hope it explaines what i mean
public class Stacks {
/*
* constructs a stack object
* #param n that will determine that size of the stacks to be constructed
*/
public Stacks(int n)
{
this.elemetns= new int[n];
this.size=n;
this.top=-1;
}
/*
* constructs a stack object, with size of 2 when no parameter is given
*/
public Stacks()
{
this.elemetns= new int[2];
this.size=2;
this.top=-1;
}
public int pop()
{
if (top<0)
{
System.out.println("Error code 2: Empty stacks");
return -1;
}
else
{
int n= this.elemetns[top];
top--;
return n;
}
}
public int [] pop(int size)
{
if (this.size<size)
{
System.out.println("Error code 3: The Maximum number of elements that can be acquired is "+ this.size);
return null;
}
else
{
int res[]= new int[size];
for (int i=0;i<size;i++)
{
res[i]=pop();
}
return res;
}
}
public void push(int e)
{
if (!isFull())
{
this.elemetns[++top]=e;
System.out.println(e+" has been pushed to the stack ");
}
else
{
updateStacksSize(this);
this.elemetns[++top]=e;
System.out.println(e+" has been pushed to the stack ");
}
}
public void push(int n,int [] ar)
{
for (int i=0;i<n;i++)
this.push(ar[i]);
}
private void updateStacksSize(Stacks s)
{
int newSize= s.top*2;
Stacks newStacks= new Stacks(newSize);
for (int i = s.top; i>-1;i--)
newStacks.elemetns[i]=s.pop();
s= newStacks;//shouldnt newStacks get garbage collected
//and s gets the new address and attributes of newStacks?
}
private boolean isFull(){return this.size==(this.top+1);}
public static void main(String[] args)
{
Stacks s= new Stacks(5);
for (int i=0;i<7;i++)
s.push(i+1);
System.out.println();
int []arr= s.pop(6);
for (int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
private int elemetns[];
private int top;
private int size;
}
Why does running this program results in problem with the old size although the current object's has been updated.
one more question is it possible to assign this= newStacks instead of instantiating new Stacks object
In Java you assign object references to variables.
I have done all that only my problem is when assigning object A to object B doesn't that mean that A will now points to the address of B?
s= newStacks;//shouldnt newStacks get garbage collected
//and s gets the new address and attributes of newStacks?
It is the other way around since the assignment in Java is from right to left.
"I have done all that only my problem is when assigning object A to object B doesn't that mean that A will now points to the address of B?"
if this is what you meant then:
Stacks A = new Stacks();
Stacks B = A;
Then what this means is that B is now pointing to A.
You're kinda over do it. A stack should consist of a chain of nodes, like an singel-linked list of nodes. I've written an example on this below, see if you can see how it works.
public class Stack <E> {
private StackItem<E> currTop;
private int size;
private int max;
private static class StackItem<E> {
private E e;
private StackItem<E> next;
}
public Stack(int max) {
currTop = null;
size = 0;
this.max = max;
}
public void add(E e){
if ((size+1) == max) throw new StackOverflowError("Max items in stack is reached");
StackItem<E> old = currTop;
currTop = new StackItem<>();
currTop.e = e;
currTop.next = old;
size++;
}
public E getFirst() {
if (currTop == null) return null;
E output = currTop.e;
currTop = currTop.next;
size --;
return output;
}
public E showFirst() {
return currTop.e;
}
public int getSize() {
return size;
}
}

Chapter 13 ex 12 and main project 1. Structure and Algorithm in Java by Frank

import.util.Arrays;
public class AList<T> implements ListInterface<T>{
private T[] list;
private int numberOfEntries;
private static final int DEFAILT_INI_CAPACITY=25;
public AList()
{
this(DEFAILT_INI_CAPACIT);
}
public AList
{
numberOfEntries = 0;
// the cast is safe because the new array contains null entries
#SuppressWarnings("unchecked")
T[] tempList = (T[])new Object[initialCapacity];
list = tempList;
}
public void add(T newEntry) {
ensureCapacity();
list[numberOfEntries] = newEntry;
numberOfEntries++;
} // end add
public int getLength() {
return numberOfEntries;
} // end getLength
public boolean isEmpty() {
return numberOfEntries == 0; // or getLength() == 0
} // end isEmpty
public T[] toArray() {
// the cast is safe because the new array contains null entries
#SuppressWarnings("unchecked")
T[] result = (T[])new Object[numberOfEntries];
for (int index = 0; index < numberOfEntries; index++) {
result[index] = list[index];
} // end for
return result;
} // end toArray
Prolbems from Data Strucutre and Algorithum in Java by Frank.
On chapter 13 exercise 12 I'm stuck on the following:
the following method Reduce the size of the array:
private boolean isTooBig()
This method return true if the number if entries in the list is less than half the size of the array and the size of the array is greater than 20.
The second new method creates a new array that is three quarters the size of the current array and then copies the object in the list of the new array:
private void reduceArray()
My Attempt:
private boolean isTooBig()
{
int half = (2 / getLenght());;
return ((numberOfEntries < half) && (numberOfEntries > 20));
}
private void reduceArray()
{
private T[] list2;
stuck...
}
My question: I do not know what is The array that I am reducing.
After I reduce the array. I do not know how to copy an ArrayList to another ArrayList.
Also I am stuck on Main project one.
1) Write a program that thoroughly tests the class AList.
My attempt:
public class test {
public static void main(String[] args)
{
AList<integer> listOfInt = new AList<integer>();
listOfInt.add(1);
listOfInt.add(2);
System.out.println(listOfInt);
}
The output is the address of listOfInt, but I want the literal value 1,2 to be printed.

Adding elements to an array without arrayList

I am trying to define a method called add() that adds an object Fish to an array fish[]. How would I got about this without using arrayList? I keep receiving the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
public class Pond {
private Fish[] fish;
private int numFish ;
private int capacity;
public Pond(int capacity){
this.capacity = capacity;
}
public int getNumFish(){ return numFish;
}
public boolean isFull(){//Ponds can only have so many fish
boolean Full = false;
if (numFish >= capacity){
Full = true;}
return Full;
}
public void add(Fish aFish) {// puts a fish in the pond--OR-- replaces a fish that has been temporarily removed
if (numFish < capacity){
fish[numFish++] = aFish;}
}
Here dynamic array solution, which is a simple implementation of ArrayList method.
public void add(Fish aFish) {
ensureCapacity();
fish[numFish++] = aFish;
}
private void ensureCapacity() {
if (numFish == fish.length) {
int newSize = fish.length * 2;
Fish[] newFish = new Fish[newSize];
System.arraycopy(fish, 0, newFish, 0, fish.length);
fish = newFish;
}
}
In your constructor for pond you can add fish = new Fish[capacity] to set the initial size of the fish array to the capacity of your pond. Remember you can not add values to an array only change the values already there.

Initialization of class array

class max{
public int buy;
public int sell;
public max(int n){
buy=0;
sell=0;
}
}
public class MaxProfit{
public void stock(int a[],int n){
max[] sol=new max[n/2+1];
if(n==1||n==0)
{
return;
}
int i=0,count=0;
while(i<n-1){
while((i<n-1)&&(a[i+1]<=a[i]))
i++;
if(i==n-1)
break;
//System.out.println(sol[count].buy=i++);
sol[count].buy=i++;
i++;
while((i<n)&&(a[i]>=a[i-1]))
i++;
sol[count].sell=i-1;
count++;
}
for(int k=0;k<count;k++)
System.out.println(sol[k].buy +sol[k].sell);
}
public static void main(String []args){
MaxProfit f=new MaxProfit();
int arr[]={20,100,260};
f.stock(arr,arr.length);
System.out.println("Hello World");
}
}
A Exception is coming which is exception in thread "main" java.lang.NullPointerException
at MaxProfit.stock(MaxProfit.java:15)
at MaxProfit.main(MaxProfit.java:32)
I am not able to solve this I have initialized array of max still I am getting null pointer exception Please help
You should initialize the elements of max[] sol maybe in a loop.
for(int i=0;i<sol.length;i++){
sol[i]=new max(aValue);
}
You are declaring an array (sol) but you are not filling your array with objects max. before using your array fill it first. Just add this to initialize your array:
max[] sol=new max[n/2+1];
for(int i = 0; i < sol.length; i++) {
sol[i] = new max(i /* or whatever the value that must be here */);
}
max[] sol=new max[n/2+1];
just defines and array with no (null) contents. You must put valid max objects in it. Like
max[i] = new max(/*param*/);
sol[count].buy=i++;
is throwing the NPE
public void stock(int a[],int n){
max[] sol=new max[n/2+1];
if(n==1||n==0)
{
return;
}
for (int k = 0; k < sol.length; k++) {
sol[k]= new max(k);
}
int i=0,count=0;
while(i<n-1){

Categories