Reason for java.lang.ArrayIndexOutOfBoundsException - java

Any idea what is wrong with this line? outStr[i]=(String) s.pop();
import java.util.ArrayList;
import java.util.Scanner;
public class StringWordReverse {
public String[] StringToWord(){
Scanner sc = new Scanner(System.in);
sc.useDelimiter(" ");
ArrayList<String> wordList= new ArrayList<String>();
String sc_in= sc.nextLine();
String[] sc_split=sc_in.split(" +");
for (int i=0; i<sc_split.length; i++){
wordList.add(sc_split[i]);
}
String[] stringArr= new String[wordList.size()];
for (int i=0; i<wordList.size(); i++){
stringArr[i]= wordList.get(i);
}
return stringArr;
}
public String[] reverseWords(String[] words){
Stack<String> s= new Stack<String>();
String[] outStr=new String[words.length];
for (int i=0; i<words.length; i++){
s.push(words[i]);
}
for (int i=0; i<words.length; i++){
System.out.println(s.stackSize());
outStr[i]=(String) s.pop();
}
return outStr;
}
public static void main(String[] argc){
StringWordReverse swr = new StringWordReverse();
String[] inputWords= swr.StringToWord();
String[] outputWords=swr.reverseWords(inputWords);
for (int i=0; i<outputWords.length;i++)
System.out.println(outputWords[i]);
return;
}
}
And here is my Stack class:
import java.util.ArrayList;
public class Stack<E> {
private ArrayList<E> s = new ArrayList<E>();
private static int size=0;
public void push(E item){
s.add(item);
size++;
return;
}
public E pop(){
size--;
return s.remove(size-1);
}
public int stackSize(){
return size;
}
}
Here's the error I receive:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.ArrayList.elementData(ArrayList.java:400)
at java.util.ArrayList.remove(ArrayList.java:477)
at XYZ.Stack.pop(Stack.java:16)
at XYZ.StringWordReverse.reverseWords(StringWordReverse.java:35)
at XYZ.StringWordReverse.main(StringWordReverse.java:47)

Some wrong things in this code :
you use raw types instead of generics. Let the compiler help you with (most) runtime type error : Stack<String> stack = new Stack<>()
in Stack.pop, you never check you have an element to pop. You should test it and throw an exception such as NoSuchElementException if the stack is empty.
in Stack.pop, you are decrementing the size and then removing item size - 1, so you basically decremented twice. This should be : s.remove(--size);

You are decreasing your size variable before you take the item from the stack using the same size variable. So when you call pop with one item left, you reduce size to 0 and then are trying to remove the item at position -1.
Why maintain your own size variable when you already have one as part of the list?

try changing this part of the code:
public E pop(){
size--;
return s.remove(size-1);
}
to this:
public E pop(){
return s.remove(size--);
}
thats the error.

Related

Why am I getting wrong 0 index of value?

I am trying to learn how to add dynamically data into a list but I am facing a problem.
Why am I getting wrong value index of 0. when ever I trying to add a value position of index.
import java.util.*;
public class MyList{
String[] mList = null;
int pointer;
public MyList(){
mList = new String[pointer];
}
public void add(String aStringValue){
System.out.println("add: "+pointer+ " " +aStringValue+ " "+mList.length);
if (pointer < mList.length-1) {
System.out.println(pointer+ " " +aStringValue);
mList[pointer] = aStringValue;
pointer++;
}else{
System.out.println("New List:");
String[] lStringList = new String[mList.length + 20];
System.arraycopy(mList, 0, lStringList, 0, mList.length);
mList = lStringList;
System.out.println("New List: "+mList.length);
}
}
public int size(){
int size = 0;
for (int i = 0;i<mList.length;i++) {
if (mList[i] == null) {
return size;
}else{
size++;
}
}
return size;
}
public String get(int index){
return mList[index];
}
}
public class ListSize{
public static void main(String[] args){
MyList lList = new MyList();
lList.add("Amit");
lList.add("Deepak");
lList.add("Vishal");
lList.add("hello");
lList.add("abc");
lList.add("rahul");
lList.add("ajit");
lList.add("durgesh");
lList.add("a");
lList.add("b");
lList.add("c");
lList.add("d");
lList.add("e");
System.out.println("MyList is: "+lList.size());
for (int i = 0; i<lList.size(); i++) {
System.out.println(lList.get(i));
}
}
}
I expect the Output of Amit, Deepak but the Actual output is Deepak, vishal
When you create a new array, you don't add anything to it. I suggest you always check the size is ok, and afterwards, always add the element. If you want to see this clearly, I suggest stepping through the code in your debugger.
public void add(String aStringValue) {
// ensure capacity.
if (pointer == mList.length)
mList = Arrays.copyOf(mList, mList.length + 20);
mList[pointer++] = aStringValue;
}
In your add method, if the array hasn’t got room for the string you want to add, you are creating a new and bigger array, but not adding the string to the new array.
I believe that the code in the if part of your if statement should go after the if statement instead.

java programming Exception in thread "main" what is this error?

I wrote this program to find the item and then to remove all elements which are smaller than the item. The are no compilation errors, but when I run the program, the following message appears.
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.remove(ArrayList.java:492)
at bb.deleteValues(bb.java:15)
at bb.main(bb.java:33)
Process completed. "
Code:
import java.util.ArrayList;
import java.util.Scanner;
public class bb {
public static boolean deleteValues(ArrayList<Integer> list, int item)
{ int p =list.indexOf(item);
if(!list.contains(item))
return false;
else
for(int i=p; i<list.size();i++ )
{int n=list.get(i);
if (n>list.get(i+1))
list.remove(p);
list.remove(i+1);
}
return true;
}
public static void main(String[] args) {
ArrayList<Integer> a= new ArrayList<Integer>(8);
a.add(3);
a.add(10);
a.add(4);
a.add(5);
a.add(3);
a.add(2);
a.add(8);
a.add(6);
a.add(4);
if(deleteValues(a,4))
for(int x : a)
System.out.print(x+ " ");
}
}
Your deleteValues method loops i from p to list.size()-1, but the loop's body contains list.get(i+1) and list.remove(i+1), so when i==list.size()-1, list.get(i+1) and list.remove(i+1) will attempt to access an item from an index not present in the list, which is the cause of the exception.
Removing the elements smaller than the passed item requires iterating over all the elements in the list, and comparing each one to the passed item. Note that when you remove the i'th element from the list, the (i+1)'th element becomes the new i'th element. That's why i should be incremented only if you don't remove an element from the list.
public static boolean deleteValues(ArrayList<Integer> list, int item)
{
int p = list.indexOf(item);
if(p<0)
return false;
for(int i=0; i<list.size();) {
if (list.get(i) < item) {
list.remove(i);
} else {
i++;
}
}
return true;
}
list.remove(i+1); will exceed the list size. For ex, when you are passing the 4th element, it will search for the element at 5th postion
The problem is in your deleteValues function, you loop while i is less than the size of the ArrayList, but add 1 when you call the get function, which can and will cause an IndexOutOfBoundsException, because it can make i equal to the size of the ArrayList, which is invalid. Change your for loop, and remove the cases where you have i+1, like so:
for(int i=p; i<list.size();i++ )
{
int n=list.get(i);
if (n>list.get(i))
list.remove(p);
list.remove(i);
}
Also, if your function is meant to remove all copies of a certain value, the code can be much, much simpler, and clearer:
public static boolean deleteValues(ArrayList<Integer> list, int item)
{
if (list.contains(item))
{
for (int i = 0; i < list.size(); i++)
if (list.get(i) == item)
list.remove(i);
return true;
}
return false;
}
import java.util.ArrayList;
import java.util.Scanner;
public class Ex {
public static boolean deleteValues(ArrayList<Integer> list)
{
for(int i=0; i<list.size();i++ )
{int n=list.get(i);
if (n>list.get(i+1))
// list.remove(i);
list.remove(i+1);
}
return true;
}
public static void main(String[] args) {
ArrayList<Integer> a= new ArrayList<Integer>(8);
a.add(3);
a.add(10);
a.add(4);
a.add(5);
a.add(3);
a.add(2);
a.add(8);
a.add(6);
// a.add(4);
if(deleteValues(a))
for(int x : a)
System.out.print(x+ " ");
}
}
you are adding one extra object to the arraylist with itz size specified and you are using index values wrongly in the deleteValues method so plz check with the both codes.
import java.util.ArrayList;
import java.util.Scanner;
public class Ex {
public static boolean deleteValues(ArrayList<Integer> list, int item)
{ int p =list.indexOf(item);
if(!list.contains(item))
return false;
else
for(int i=0; i<list.size();i++ )
{int n=list.get(i);
if (n>list.get(i+1))
list.remove(p);
//list.remove(i+1);
}
return true;
}
public static void main(String[] args) {
ArrayList<Integer> a= new ArrayList<Integer>(8);
a.add(3);
a.add(10);
a.add(4);
a.add(5);
a.add(3);
a.add(2);
a.add(8);
//a.add(6);
a.add(4);
if(deleteValues(a,4))
for(int x : a)
System.out.print(x+ " ");
}
}

Finding index out of bounds exception

All was well with this program until I made some changes in my addMainMenu method. Now it seems as though there is an array index out of bounds somewhere. Eclipse is not leading me too it. Does anyone know why this code has an array index out of bounds exception.
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.LinkedList.checkElementIndex(Unknown Source)
at java.util.LinkedList.get(Unknown Source)
at Menu.main(Menu.java:58)
import java.util.LinkedList;
import java.util.List;
public class Menu {
LinkedList <LinkedList> mainMenuItems = new LinkedList <LinkedList> ();
public void Menu(){}
public boolean addMainMenuItem(String newItem, String existingItem, int position){
LinkedList <String> subMenuItems = new LinkedList <String> ();
for (int i = 0; i<= mainMenuItems.size(); i++){
if (mainMenuItems.get(i).contains(existingItem)){
subMenuItems.addLast(newItem);
int existingIndex = mainMenuItems.indexOf(existingItem);
if (position == 1){
mainMenuItems.add(existingIndex + 1, subMenuItems);
break;
}
if (position == -1){
mainMenuItems.add(existingIndex, subMenuItems);
break;
}
if (i == mainMenuItems.size()){
subMenuItems.addLast(newItem);
mainMenuItems.add(subMenuItems);
break;
}
}
}
}
return true;
}
public boolean deleteMainMenuItem(String item){
if (mainMenuItems.contains(mainMenuItems.indexOf(item))){
mainMenuItems.remove(mainMenuItems.indexOf(item));
return true;
}
else{
return false;
}
}
public static void main(String[] args){
Menu b = new Menu();
b.addMainMenuItem("h", "b", 1);
b.addMainMenuItem("hi", "h", 1);
b.addMainMenuItem("i", "h", 1);
System.out.println(b.mainMenuItems.get(0));
b.deleteMainMenuItem("hi");
System.out.println(b.mainMenuItems.get(0));
System.out.println(b.deleteMainMenuItem("hi"));
}
There are two possible issues
1. In this line
for (int i = 0; i<= mainMenuItems.size(); i++)
you should have use i < mainMenuItems.size()
2. when you have not assigned any value to your LinkedList, you try to access an index of your LinkedList
Change the <= to < in: i<= mainMenuItems.size()
EDIT:
If mainMenuItems is still empty, the line mainMenuItems.get(i).contains(existingItem) will generate java.lang.IndexOutOfBoundsException because mainMenuItems.get(i) doesn't exist.
First - Change the for loop as shown below
for (int i = 0; i < mainMenuItems.size(); i++)
Also, you need to restructure addMainMenuItem method as shown below -
for (int i = 0; i < mainMenuItems.size(); i++){
if (mainMenuItems.size() == 0) {
//you should put list initialization code here
//means, logic when there is nothing in the mainMenuItems list
} else {
//when the list is not empty
}
}
You are getting IndexOutOfBoundsException because you are doing get(index) on mainMenuItems - which is empty in your for loop.
For example -
List<String> list = new LinkedList<String>();
list.get(0); //will throw the same exception

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

Creating a stack with an array, what am I doing wrong?

Pretty simple idea, I am just not sure why it won't work. I am getting an error when I call Stack b = new Stack(5); in main.
Here is main
public class Test {
public static void main(String[] args) {
Stack b = new Stack(5);
b.push('a');
b.push('b');
b.push('c');
b.printStack();
}
}
Here is my stack class
public class Stack {
char[] stack;
int items;
public Stack(int size) {
stack = char[size];
items = 0;
}
public void push (char add){
if (items == stack.length) {
System.out.println("Stack is full");
}
else {
stack[items] = add;
}
}
public void printStack() {
if (items == 0)
return;
else {
for (int i = 0; i < items; i++)
System.out.println(i);
}
}
}
One thing is:
public Stack(int size) {
stack = new char[size];
//^^^you missed new
items = 0;
}
Meanwhile
stack[items] = add; //should also increment items
You need to new up your array.
I can see that your push doesn't increment the items count. When you push onto your stack, you should also increment the count.
in your constructor use
stack = new char[size];
You are not using the new keyword when creating your stack array in the constructor.
Furthermore, your push() method does not increment items, and thus will simply constantly overwrite the first element of the stack array.
Finally, your printStack() method will not function as you expect it to. Rather, it will print incremental digits up to the number 5. You will need to change the print statement for it to work.
System.out.println(stack[i]);

Categories

Resources