Index out of Bounds Exception in Stack Data Structure - java

I am writing a program to reverse a word using a stack data structure. The way it's supposed to work is that I input a string, insert each character of the string in a stack object, then I would pop each object out of the stack and print them. The word will be in the reverse order of the original input since that's just how stacks work.
I keep getting an index out of bounds exception; debugging makes me suspect that it has to do with the initial array initialization within the Stack class, but it could also have to do with the push() function.
Here's the entire code:
public class Stack // object to emulate stack data structure
{
private int stackMaxSize;
private char stackArray[];
private int currentSize;
public Stack() // if initialized without any parameters
{
this(100);
}
public Stack(int maxSize) // if initialized with parameter
{
maxSize = stackMaxSize;
stackArray = new char[stackMaxSize];
currentSize = -1;
}
public void push(char c) //pushes new character into stack
{
stackArray[++currentSize] = c;
}
public char pop() //pops character out of stack
{
return stackArray[currentSize--];
}
public char peek() // returns character on top of stack
{
return stackArray[currentSize];
}
public boolean isEmpty() // returns whether stack is empty or not
{
return (currentSize < 0);
}
}
and here's the main:
import java.util.Scanner;
public class ReverseWord
{
public static void main(String[] args)
{
Stack wordStack = new Stack(100); // default size is 100
System.out.print("Enter the word to be reversed: ");
String word = getString();
for (byte i = 0; i <= word.length(); i++) // inserts word into stack char by char
{
wordStack.push(word.charAt(i));
}
System.out.print(wordStack.pop());
}
static String getString()
{
Scanner input = new Scanner(System.in);
String s = input.nextLine();
return s;
}
}
Thanks a lot!
JLL

In your Stack(int) constructor
maxSize = stackMaxSize;
should be
stackMaxSize = maxSize;

The corrected and working code as follows: (Note that, the main function is written in Stack class for simplicity and corrected code lines are commented)
public class Stack // object to emulate stack data structure
{
private final int stackMaxSize;
private final char stackArray[];
private int currentSize;
public Stack() // if initialized without any parameters
{
this(100);
}
public Stack(final int maxSize) // if initialized with parameter
{
this.stackMaxSize = maxSize; /* corrected: assignment reversed */
this.stackArray = new char[this.stackMaxSize];
this.currentSize = -1;
}
public void push(final char c) // pushes new character into stack
{
this.stackArray[++this.currentSize] = c;
}
public char pop() // pops character out of stack
{
return this.stackArray[this.currentSize--];
}
public char peek() // returns character on top of stack
{
return this.stackArray[this.currentSize];
}
public boolean isEmpty() // returns whether stack is empty or not
{
return this.currentSize < 0;
}
public static void main(final String[] args) {
Stack wordStack = new Stack(100); // default size is 100
System.out.print("Enter the word to be reversed: ");
String word = getString();
/* corrected: i <= word.length() >> i < word.length() */
for (byte i = 0; i < word.length(); i++) // inserts word into stack char by char
{
wordStack.push(word.charAt(i));
}
/* corrected: while loop added to consume the entire stack */
while (!wordStack.isEmpty()) {
System.out.print(wordStack.pop());
}
}
static String getString() {
Scanner input = new Scanner(System.in);
String s = input.nextLine();
return s;
}
}

The problems with the original program was that:
1) For loop should be:
for (byte i = 0; i < word.length(); i++)
instead of <= (thanks to ovunccetin)
2) In the constructor of the Stack class
maxSize = stackMaxSize;
should be:
stackMaxSize = maxSize;
Thanks to Ravi Thapliyal

Related

Performing stack operation to push string in java without collection api

In my java program I want to perform stack operation like push and pop. I also want to push string in stack operation but when I try to push string. I get error mentioned in screenshot. How should I change push method in order to run the program successfully.
code ::
public class DataStack {
private static final int capacity = 3;
String arr[] = new String[capacity];
int top = -1;
public void push(String pushedElement) {
if (top < capacity - 1) {
top++;
arr[top] = pushedElement;
printElements();
} else {
System.out.println("Stack Overflow !");
}
}
public void pop() {
if (top >= 0) {
top--;
System.out.println("Pop operation done !");
} else {
System.out.println("Stack Underflow !");
}
}
public void printElements() {
if (top >= 0) {
System.out.print("Elements in stack : ");
for (int i = 0; i <= top; i++) {
System.out.println(arr[i]);
}
}
}
public static void main(String[] args) {
DataStack stackDemo = new DataStack();
stackDemo.push("china");
stackDemo.push("india");
stackDemo.push("usa");
}
}
Error::
Your push() method and underlying arr variable should be of String type.
String arr[] = new String[capacity];
public void push(String pushedElement) {
...
}
Your array is declared to store only integers . Not to mention, the stackDemo.push method also declared to take in only int arguments.
int arr[] = new int[capacity];
public void push(int pushedElement) {
you should try pushing in integers.
stackDemo.push(1);
stackDemo.push(2);
stackDemo.push(3);

I am having trouble char array in java

I wrote this code. My aim is to write the string in char.
But i'm getting ArrayIndexOfBoundsException error.
public class Charwork {
char[] letter;
int keepInt;
public Charwork()
{
letter = new char[keepInt];
}
public void copy(String nameToCoppy)
{
this.keepInt = nameToCoppy.length();
System.out.println(this.keepInt);
for(int x = 0; x < this.keepInt;x++)
{
letter[x] = nameToCoppy.charAt(x);
System.out.println(letter[x]);
}
}
}
Your issue is your array is instantiated with a int that is null or 0. Moving that one line in your constructor to the copy function after getting string length should do the trick.
public Charwork()
{
}
public void copy(String nameToCoppy)
{
this.keepInt = nameToCoppy.length();
letter = new char[keepInt];
System.out.println(this.keepInt);
for(int x = 0; x < this.keepInt;x++)
{
letter[x] = nameToCoppy.charAt(x);
System.out.println(letter[x]);
}
}
You create an object Charworkwhile instantiating variable char[] letter with length keepInt - but keepInt is zero at the moment, beacuse int is primitive and instantinated with default 0 value.
Then, in copy method you change value of keepInt, but that's irrelevant, because an array char[] letter is already set with length 0.

Printing an Array as a String with 10 elements per line

// Line in Main Code
public class Assignment7 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input;
char userChoice;
int newVal, index;
IntegerList intList = null;
printMenu();
do {
System.out.print("Please enter a command or type? ");
input = scan.nextLine();
if (input.length() != 0)
userChoice = input.charAt(0);
else
userChoice = ' ';
switch (userChoice) {
case 'a':
System.out.print("How big should the list be? ");
intList = new IntegerList(scan.nextInt());
scan.nextLine();
System.out.print("What is range of the values for each random draw? ");
intList.randomize(scan.nextInt());
scan.nextLine();
break;
case 'b':
System.out.println(intList.toStrng());
break;
The above code is part of my main code, where I get user input and as them to set the boundary conditions of the array. case 'b' asks to print out the array by calling the function in the class which should return the array as a string with 10 elements per line.
// line in class
import java.util.Arrays;
import java.util.Random;
public class IntegerList {
private int arrSize;
public IntegerList(int size) {
size = arrSize;
}
private int[] IntArray = new int[arrSize];
public void randomize (int num) {
for(int i = 0;i<IntArray.length;i++) {
IntArray[i] =(int) (Math.random()*(num+1));
}
}
public void addElement(int newVal, int index) {
for(int i = index;i<IntArray.length;i++) {
int temp = IntArray[i];
IntArray[i]=newVal;
IntArray[i+1]=temp;
if(i == IntArray.length){
increaseSize(IntArray);
}
}
}
private static void increaseSize(int[] x) {
int[] temp = new int[2*x.length];
for(int i = 0; i<x.length;i++) {
temp[i]=x[i];
}
x = temp;
}
public void removeFirst(int nextInt) {
// TODO Auto-generated method stub
}
public String range() {
// TODO Auto-generated method stub
return null;
}
public String toStrng() {
String arrayOut = " ";
for(int i = 0; i<IntArray.length; i++ ) {
if(i%10 == 0 ) {
arrayOut+="\n";
}
arrayOut += IntArray[i] + " " ;
}
return arrayOut;
}
}
I'm trying to convert the array into a string and then return int and have it display 10 elements per line. I'm pretty sure I have the logic right, however, when I run the code, it does not display the array at all. How should I go about fixing this?
Look at how you are creating your array of integers through your current constructor...
public IntegerList(int size) {
size = arrSize;
}
private int[] IntArray = new int[arrSize];
When you call
intList = new IntegerList(scan.nextInt());
in your menu program, your array list won't magically know it needs to be re-initialized. It will be 0 since the value of arrSize is always 0 when you create your IntegerList object. Furthermore you have the assignment of the variables switched. Change your constructor to the following
private int[] IntArray = null;
public IntegerList(int size) {
arrSize = size;
IntArray = new int[arrSize];
}
Everything seems to work because the size of your array was always 0 and your methods just return.
You did not initialize your arrSize
You can modify your constructor to initialize arrSize
public IntegerList(int size) {
arrSize = size;
}
Also, in you toStrng method, you can just make use of arrSize instead of IntArray.length

swapping of numbers using index in java is not working

package dspermutation;
import java.util.Scanner;
public class DSPermutation {
String s;
char[] c;
int n;
public static void main(String[] args) {
DSPermutation ds=new DSPermutation();
ds.input();
}
private void input() {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the string");
s=sc.next();
c=s.toCharArray();
n=c.length;
permutation(c,n-1,0);
}
private void permutation(char[] cc,int nn,int ii) {
if(ii==nn)
{
System.out.println(cc);
}
else
{
for(int j=ii;j<=nn;j++)
{
swap(cc[ii],cc[j]);
permutation(cc,nn,ii+1);
swap(cc[ii],cc[j]);
}
}
}
private void swap(char p, char c0) {
int x=s.indexOf(p);
int y=s.indexOf(c0);
/*1*/ char temp=c[x];
/*2*/c[x]=c[y];
/*3*/c[y]=temp;
/*c[x]=c0;
c[y]=p;*/
}
}
The above program is for printing all permutations of a given string.The result is coming true but in swap() method if i replace line 1,2,3(written in comment) by logic written in comment(after line 1,2,3) then answer comes wrong. Why could this be happening?
Your mistake is assuming c[x] == p and c[y] == c0. But the indexes x and y are derived from the immutable string s, which doesn't reflect the values in c in its shuffled state.
You are swapping values of character array using immutable string's position (i.e String always holds the same initial values). To make your commented code work you have to add this s = String.valueOf(c);at the end of swap function.
private void swap(char p, char c0) {
int x = s.indexOf(p);
int y = s.indexOf(c0);
// char temp = c[x];
// c[x] = c[y];
// c[y] = temp;
c[y] = p;
c[x] = c0;
s = String.valueOf(c);
}

How can i resolve the Exception in thread "main" java.lang.ArrayndexOutOfBoundsException [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm Java beginner, I have taken piece of code from online and trying the program on permutation. Im getting error as
Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException: -1.
Can anybody help to resolve this problem. Thank you.
// Permute.java -- A class generating all permutations
import java.lang.reflect.Array;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Permute implements Iterator {
private final int size;
private final Object [] elements; // copy of original 0 .. size-1
private final Object ar; // array for output, 0 .. size-1
private final int [] permutation; // perm of nums 1..size, perm[0]=0
private boolean next = true;
// int[], double[] array won't work :-(
public Permute (Object [] e) {
size = e.length;
elements = new Object [size]; // not suitable for primitives
System.arraycopy (e, 0, elements, 0, size);
ar = Array.newInstance (e.getClass().getComponentType(), size);
System.arraycopy (e, 0, ar, 0, size);
permutation = new int [size+1];
for (int i=0; i<size+1; i++) {
permutation [i]=i;
}
}
private void formNextPermutation () {
for (int i=0; i<size; i++) {
// i+1 because perm[0] always = 0
// perm[]-1 because the numbers 1..size are being permuted
Array.set (ar, i, elements[permutation[i+1]-1]);
}
}
public boolean hasNext() {
return next;
}
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
private void swap (final int i, final int j) {
final int x = permutation[i];
permutation[i] = permutation [j];
permutation[j] = x;
}
// does not throw NoSuchElement; it wraps around!
public Object next() throws NoSuchElementException {
formNextPermutation (); // copy original elements
int i = size-1;
while (permutation[i]>permutation[i+1])
i--;
if (i==0) {
next = false;
for (int j=0; j<size+1; j++) {
permutation [j]=j;
}
return ar;
}
int j = size;
while (permutation[i]>permutation[j]) j--;
swap (i,j);
int r = size;
int s = i+1;
while (r>s) { swap(r,s); r--; s++; }
return ar;
}
public String toString () {
final int n = Array.getLength(ar);
final StringBuffer sb = new StringBuffer ("[");
for (int j=0; j<n; j++) {
sb.append (Array.get(ar,j).toString());
if (j<n-1) sb.append (",");
}
sb.append("]");
return new String (sb);
}
public static void main (String [] args) {
for (Iterator i = new Permute(args); i.hasNext(); ) {
final String [] a = (String []) i.next();
System.out.println (i);
}
}
}
ArrayIndexOutOfBoundsException Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
As you have not posted any stack trace. Problem is unclear. But these links may help you.
oracle docs
stackoverflow

Categories

Resources