ArrayList and IndexOutOfBounds exception - java

So I'm getting an index out of bounds exception on some code i'm writing. What I don't understand is that I know for a fact that the index element I'm trying to work with exists.
Here's the code:
I have a constructor for an array list
public StixBoard(int number)
{
stixGame = new ArrayList<Integer>(number);
for (int i = 0; i < number; i++)
{
stixGame.add(i);
}
}
This block generates a random variable 1-3
public int computeMove()
{
int numberOfStix = (int) (3.0 * Math.random()) + 1;
return numberOfStix;
}
Really straight forward, now here I have a method that takes the parameter supplied and attempts to remove those number of elements from the array list. As you can see, the parameter must be between 1 and 3, and it must be less than or equal to the size of the array list. Otherwise, the user is prompted to enter another number
public boolean takeStix(int number)
{
boolean logicVar = false;
placeHolder = stixGame.size();
if ((number >= 1 && number <= 3) && number <= placeHolder)
{
for (int i = 0; i < number; i++)
{
stixGame.remove(i);
logicVar = true;
}
} else if (number > 3 || number > placeHolder)
{
do
{
System.out
.println("Please enter a different number, less than or equal to three.");
Scanner numberScan = new Scanner(System.in);
number = numberScan.nextInt();
} while (number > 3 || number > placeHolder);
}
return logicVar;
}
So as this program runs, the computeMove() method generates a random int (assuming the role of a computerized player) and attempts to translate that value to the number of indexes to be removed from the array list.
This ultimately brings me to this:
How many stix on the table? 4
|||||||||| 4 stix on the table
It's the computer's turn!
The computer chose 3
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.remove(ArrayList.java:387)
at StixBoard.takeStix(StixBoard.java:38)
at StixGame.main(StixGame.java:55)
So as you can see, the array list is of size 4, but when the computer rolls a 3, (which should leave me with 1), I am left with this error. How does my array list go from being of size 4 indexes to size 2?

You iterate through your list, from beginning to end, and remove an element at each step. This makes all the elements in the list shift to the left.
First iteration: i = 0
[1, 2, 3]
Second iteration: i = 1
[2, 3]
Third iteration: i = 2
[2] -> IndexOutOfBoudsException. There is no index 2 in this list.
Iterate from the end to the beginning instead. That willmake it correct, and faster since the list won't have to copy all the elements from right to left.

The problem is in this loop:
for (int i = 0; i < number; i++)
{
stixGame.remove(i);
logicVar = true;
}
Once you remove the elements then list size is also decreased. If you start with list size 3 then in 3rd iteration, the index becomes 2 as initially 0 then 1 then 2 while size becomes 1 as intially 3 then 2 then 1. Hence IndexOutOfBoundException.
Try this:
for (int i = 0; i < number; i++){
stixGame.remove(0);//remove 0th index as previous element was removed
logicVar = true;
}

Look at it this way.
When you start your for-loop the ArrayList is of size x.
When you call remove() you take an element from the list. So the size is x-1.
But if you're constantly increasing the element you're removing, eventually you'll be removing an index that no longer exists. Remember, when you call remove() the contents of the array list are shifted. So if you had 0,1,2,3 before and removed 2. The list is 0,1,3. if you call remove(4) which was valid initially, you'll get an Out Of Bounds exception

Related

Array not looping correctly - Java

I have an array with 60 values, and when I click the next button, it will cycle through all of the values of my array in ascending order until the number 60, then it starts at number one again.
I also have a previous button, so I can go down values instead of going up. When I hit the previous button on the first array value [0], my app crashes and I am not sure why.
Here is my code:
public String nextFact() {
i++;
if(i >= facts.length) {
i = 0;
}
return facts[i];
}
public String previousFact() {
i--;
if(i < 0) {
i = facts.length;
}
return facts[i];
}
You are getting an ArrayIndexOutOfBoundsException when you change i to facts.length, because valid array indexes range from 0 through facts.length - 1. Set i to facts.length - 1.
if(i < 0) {
i = facts.length - 1;
}
Your wrapping-around code for greater than or equal to the length should be working fine.
Your array is of size array.length. So the last index will be array.length-1. In your previous function, you assign array.length to i. This is larger index than max index for array and therefore it crashes down. You must be getting am indexoutofbound error too.
You should replace that line with this:
i = facts.length - 1;

Testing elements in an array

Hello I have searched for a simple way to check ,
if any number of elements up to 6 in the array add up to seven. I have yet to find one my array is this,
private int[] diceRoll = new int[6];
The question is a bit vague, however, here's my attempt at an answer:
If what you're trying to do is take two indices x and y in diceRoll[] and see if they add up to 7, the simplest thing to do is
if(diceRoll[x] + diceRoll[y] ==7){
return true;}
If you're trying to see if ANY item with any other item adds up to 7, use a double for-loop (these are weird, but very helpful)
for(int i = 0; i < diceRoll.length; i++){
for(int j = 0; i < diceRoll.length; i++){
if(diceRoll[i] + diceRoll[j] != 7){
return false;
}
}
}
Hope this helps!
-katie
It sounds like what you need to do is take every subset of the diceRoll array and see which ones add up to 7. This is how it can be done.
Assuming you know that 1 & 1 = 1, and that 1 & 0 = 0, imagine each element of the array having a number in 0 0 0 0 0, if the element is selected, say element 5, the subset representation in binary form would be 0 0 0 0 1. If element 2 and 3 are selected, the subset representation would be 0 0 1 1 0. If you take a binary one, keep track of its index, and move it from right to left in the array computing index&1 each time, you can get which indexes of the array are in the current subset (if the index&1 computation results in a 1 for that index). Translating this to a smaller array called currSubset, you can sum it up and check if it is equal to 7.
The termination of the outer for loop comes from the maximum value of a 5 digit binary number, which is 11111 = 31 = 2^5-1, hence the use of the less than sign.
int sum = 0;
int index = 0;
ArrayList<ArrayList<Integer>> subsetsThatAddTo7 = new ArrayList<ArrayList<Integer>>();
for(int subsetRep = 0b00001; i < Math.pow(2,5); i++){
ArrayList<Integer> currSubset = new ArrayList<Integer>
for(index = 0; index < 5; index++){
if(subsetRep & (1 << index))
currSubset.add(diceRoll[5-index]);
}
int sum = 0;
for(int num : currSubset)
sum += num;
if(sum == 7)
subsetsThatAddTo7.add(currSubset);
}

Algorithm sometimes works

I am currently trying to set up a sorting algorithm for an array that scans for the highest and lowest number and places them into a new array, two at a time. I've noticed that it appears to work only in certain conditions. For example, I can input it as {5, 3, 10, 7} or {3, 5, 10, 7}, but {7, 3, 5, 10} produces an IndexOutOfBoundsException: index 1, size: 1;
Here's the code:
import java.util.Scanner; // program uses class Scanner
import java.util.ArrayList; //helps with arrays
public class ArrayAlg
{
// main method begins execution of Java application
public static void main( String[] args )
{
// create a Scanner to obtain input from the command window
Scanner input = new Scanner( System.in );
boolean AS = false; //array sorted.
int hi = 0; //high number
int low = 100; //set to 100 for logic reasons.
int oldhi = 0;
int oldlow = 0;
int NI = 0;
int addA = 0;
int p = 0; //places, moves right after one scan to place the next int
int n = 1; //number of times, moves left after one to place the next int
String cont = "n";
ArrayList<Integer> IParray = new ArrayList<Integer>(); //input array
ArrayList<Integer> Sarray = new ArrayList<Integer>(); //sorted array
while (cont.equals("n"))
{
System.out.print("Please enter a number for the array: ");
addA = input.nextInt();
IParray.add(addA);
NI++;
System.out.print("\n is that all? (y/n): ");
cont = input.next();
}
for (int c = 0; c < NI; c++) //adds 0 so sorting will be easier
Sarray.add(0); //matches the inputted array
System.out.print("The inputted array: ");
System.out.print(IParray);
System.out.println("");
while (AS == false){
hi = 0;
low = 100;
for (int i = 0; i < IParray.size(); i++)
{
if (IParray.get(i) < low)
low = IParray.get(i);
if (IParray.get(i) > hi)
{
//if (IParray.get(i) > hi) currently commented out, doesn't effect the logic by the looks of it.
hi = IParray.get(i);
}
}//end for
Sarray.set(p, low); //sets the number in the left most position then moves to the right
Sarray.set(Sarray.size() - n, hi); //sets the number to the rightmost position and moves left
p++; //increase place count to the right
n++; //increases the place count to the left
oldhi = IParray.indexOf(hi); //oldhi becomes the index of the recent highest number.
oldlow = IParray.indexOf(low); //oldlow becomes the index of the recent lowest number
IParray.remove(oldhi); //removes the highest number at the index
IParray.remove(oldlow); //removes the lowest number at the index, exceptions occurs right here.
System.out.print("The inputted array: ");//mostly here to see what the inputted array looks like after one iteration
System.out.print(IParray);
System.out.println("");
System.out.print("The sorted array: ");
System.out.print(Sarray);
System.out.println("");
if (IParray.isEmpty() == true) //checks to see if the input array is empty
AS = true;
else
AS = false;
}//end while
} // end method main
} // end class ArrayAlg
Can anyone give me any hints on why this might be occurring? I've been trying this out for the past hour or so. Tried Googling and searching this site for answers but no luck
You are getting the index out of bounds because it is trying to remove an index that does not exist. When it is removing indexes it removes lowest first causing the whole array index to shift downwards. It does not keep it's original index.
[0] = 7
[1] = 3
[2] = 5
[3] = 10
When removing the high number, 10, it becomes:
[0] = 7
[1] = 3
[2] = 5
When removing the low number it becomes:
[0] = 7
[1] = 5
The next loop you remove 7 first leaving only 5 at index 0 but your code is calling to remove index 1 giving you an out of bounds exception.
To fix this, let it dynamically get the index when the remove method is called.
IParray.remove(IParray.indexOf(hi)); //removes the highest number at the index
IParray.remove(IParray.indexOf(low)); //removes the lowest number at the index
You should have been able to quickly find this error by running your code in debugging mode and then stepping through the code that is throwing the exception (Line 73).
You might not be able to find a higher value and lower value comparison to previous ones. For example, input array was {7, 3, 5, 10}, now hi is 10 and low is 7, they were removed from IParray.
for (int i = 0; i < IParray.size(); i++)
{
if (IParray.get(i) < low)
low = IParray.get(i); // low becomes 3
if (IParray.get(i) > hi) //!!! never able to find a higher value than 10 !!!
{
//if (IParray.get(i) > hi) currently commented out, doesn't effect the logic by the looks of it.
hi = IParray.get(i);
}
}
In that case, low and high points to previous values, which was removed from the array since last iteration, so oldhi and oldlow would be -1, and you got the exception for IParray.remove(-1)
oldhi = IParray.indexOf(hi); // 10 is not in the array anymore, you got -1
oldlow = IParray.indexOf(low);
IParray.remove(oldhi); // you got exception here as you remove(-1)
IParray.remove(oldlow);

How to insert a number into an array in java

Ok I am trying to do the following using an array.
Say I have one array
1 4 3 7 8
and at index 1 I want to place a 2 to get the following
1 2 4 3 7 8
How do I do this I think I have to make one array to keep everything before the index, one array to keep everything after the index.
And the add one more element to the array with everything before the index. The create a new longer array with everything before the index and everything after the index.
But I cannot seem to do it. This be what I tried.
//this program will test out how to replace an array with more stuff
public class Raton
{
public static void main(String[] args)
{
int[] gato={1,4,3,7,8};
int[] perro = new int[gato.length+1];
int[] biggie = new int[gato.length];
int index=2; //store item index 2
System.out.println("the contents of gato are ");
for(int i=0; i<gato.length;i++)
{
System.out.println(gato[i]);
}
for(int i=0;i<gato.length;i++)
{
if(i<index)
{
perro[i]=gato[i];
}
else
{
int red=0;
biggie[red]=gato[i];
red++;
}
}
//put two in the new place
for(int i=0;i<perro.length;i++)
{
System.out.println(" \n the contents of peero are " + perro[i]);
}
for(int i=0; i<biggie.length;i++)
{
System.out.println("\nthe contents of biggie are " + biggie[i]);
}
}
}
First you need to get both the new number and new index.
int newNumber = 2;
int newIndex = 1;
Create the new array with size+1 of old array
int[] gato = {1,4,3,7,8}; //old array
int[] perro = new int[gato.length+1]; //new array
Then keep track of of two counters. j for old array and i for new array.
int j = 0;
for(int i = 0; i<perro.length; i++){
if(i == newIndex){
perro[i] = newNumber;
}
else{
perro[i] = gato[j];
j++;
}
}
Here's a test run. This solution is assuming you have a constraint where you can only use arrays (not ArrayList or any other prebuilt classes in Java)
Use an ArrayList<Integer> instead of arrays, they allow easy insertion of new elements, and arraylists allow that at specific indices too.
int[] gato={1,4,3,7,8};
List<Integer> list = new ArrayList<>(Arrays.asList(gato));
list.add(1, 2);
I haven't tested this code, but something similar should do the trick.
public class Raton {
public static void main(String[] args) {
int[] originalArray = {1,4,3,7,8};
int[] modifiedArray = new int[originalArray.length + 1];
int index = 2;
for(int i = 0; i < (originalArray.length + 1); i++) {
if(i==1) {
modifiedArray[i] = index;
}
else if(i < 1){
modifiedArray[i] = originalArray[i];
}
else {
modifiedArray[i] = originalArray[i-1];
}
}
}
}
Try to look at the "before" and "after" arrays:
Before
┌─┬─┬─┬─┬─┐
│1│4│3│7│8│
└─┴─┴─┴─┴─┘
0 1 2 3 4
After
┌─┬─┬─┬─┬─┬─┐
│1│2│4│3│7│8│
└─┴─┴─┴─┴─┴─┘
0 1 2 3 4 5
One thing you already noticed is that you need a target array that is 1 bigger than the original array. That's correct.
But you have several problems in your program.
You copy all the parts that are before the index to perro. Since perro is your target array (the one bigger than the original), you have to make sure that everything gets copied to it. But instead, you only copy the parts that are before the index.
You want to place the 2 at index 1. But you wrote index=2. This means that both the 1 and 4 will be copied to perro consecutively. Your perro will look like this:
┌─┬─┬─┬─┬─┬─┐
│1│4│0│0│0│0│
└─┴─┴─┴─┴─┴─┘
0 1 2 3 4 5
and this means that you didn't put the 2 in the place you wanted it. That place is taken by the 4.
You try to copy the numbers after the index to biggie. But you are doing this using red. And in each iteration of the loop, you set red=0 again. So the only place in biggie that will change is 0, and that place will get all the numbers, and the last one will stay. So your biggie will be:
┌─┬─┬─┬─┬─┐
│8│0│0│0│0│
└─┴─┴─┴─┴─┘
0 1 2 3 4
You don't put the 2 anywhere!
You don't copy things from biggie to perro so you don`t get all the parts of the array together.
So let's look at our before and after arrays again:
Before
┌─┬─┬─┬─┬─┐
│1│4│3│7│8│
└─┴─┴─┴─┴─┘
0 1 2 3 4
After
┌─┬─┬─┬─┬─┬─┐
│1│2│4│3│7│8│
└─┴─┴─┴─┴─┴─┘
0 1 2 3 4 5
So first, we have to remember that the index we want to change is 1, not 2. Now look at the after array. You notice that there are three types of numbers:
Ones that stayed in the same place (the 1)
Ones that were added (the 2)
Ones that moved one place to the right (4,3,7,8)
How do we know which of the original numbers "stay" and which ones "move"? It's easy. The ones whose index is less than index (remember, it's 1!), that is, the one at index 0, stays.
All the others (including the one that is in the index itself!) have to move to a new place. The place is their old index + 1.
So your program should look like this:
Prepare an array whose size is one bigger than the original (like your perro).
Loop on all the indexes in the old array. Suppose the loop variable is i.
If i is less than the index, copy the number at index i from the original array to the new array at the same index, that is, at i.
For all other cases, copy the number at index i from the original array to the new array, but moved by one place. That is, i+1. There is no need for another variable or a ++ here.
When you finish that loop, your array will look like:
┌─┬─┬─┬─┬─┬─┐
│1│0│4│3│7│8│
└─┴─┴─┴─┴─┴─┘
0 1 2 3 4 5
Now don't forget to put your actual 2 there, at the index index!
Note: please give your variables meaningful names. I'm not sure, perhaps the names are meaningful in your native language, but biggie and red seem to be words in English, but they don't help us understand what these variables do. Try to use variable names that describe the function of the variable. Like original, target, temporary, nextIndex etc.
I think this is a clean and simple solution :
public static void main(String[] args) {
int[] gato = {1, 4, 3, 7, 8};
int index = 2; //store item index 2
System.out.println("the contents of gato are ");
for (int i = 0; i < gato.length; i++) {
System.out.println(gato[i]);
}
gato = Arrays.copyOf(gato, gato.length + 1);
for (int i = gato.length - 1; i > index; i--) {
gato[i] = gato[i - 1];
}
//put the element in the array
gato[index] = 2;
for (int i = 0; i < gato.length; i++) {
System.out.println(gato[i]);
}
}

Remove every 3rd element in arraylist

I am trying to loop through an arraylist and gradually remove an element every 3 indices. Once it gets to the end of the arraylist I want to reset the index back to the beginning, and then loop through the arraylist again, again removing an element every 3 indices until there is only one element left in the arraylist.
The listOfWords is an array with a length of 3 that was previously filled.
int listIndex = 0;
do
{
// just to display contents of arraylist
System.out.println(listOfPlayers);
for(int wordIndex = 0; wordIndex < listOfWords.length; wordIndex++
{
System.out.print("Player");
System.out.print(listOfPlayers.get(wordIndex));
System.out.println("");
listIndex = wordIndex;
}
listOfPlayers.remove(listOfPlayers.get(listIndex));
}
while(listOfPlayers.size() > 1);
I have tried to implement for several hours yet I am still having trouble. Here's what happens to the elements of the arraylist:
1, 2, 3, 4
1, 2, 4
1, 2
Then it throws an 'index out of bounds error' exception when it checks for the third element (which no longer exists). Once it reaches the last element I want it to wrap around to the first element and continue through the array. I also want it to start where it left off and not from the beginning once it removes an element from the arraylist.
Maybe I have just missed the boat, but is this what you were after?
import java.util.ArrayList;
import java.util.Random;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
Random r = new Random();
//Populate array with ten random elements
for(int i = 0 ; i < 4; i++){
numbers.add(r.nextInt());
}
while(numbers.size() > 1){
for(int i = 0; i < numbers.size();i++){
if(i%3 == 0){//Every 3rd element should be true
numbers.remove(i);
}
}
}
}
}
You could move every third element to a temporary list then use List#removeAll(Collection) to remove the items when you finish each loop...until the master list was empty...
Lets back up and look at the problem algorithmically.
Start at the first item and start counting.
Go to the next item and increment your count. If there is no next item, go to the beginning.
If the count is '3', delete that item and reset count. (Or modulo.)
If there is one item left in the list, stop.
Lets write pseudocode:
function (takes a list)
remember what index in that list we're at
remember whether this is the item we want to delete.
loop until the list is size 1
increment the item we're looking at.
increment the delete count we're on
should we delete?
if so, delete!
reset delete count
are we at the end of the list?
if so, reset our index
Looking at it this way, it's fairly easy to translate this immediately into code:
public void doIt(List<String> arrayList) {
int index = 0;
int count = 0;
while(arrayList.size() != 1) {
index = index + 1;
count = count + 1; //increment count
String word = arrayList.get(index);//get next item, and do stuff with it
if (count == 3) {
//note that the [Java API][1] allows you to remove by index
arrayList.remove(index - 1);//otherwise you'll get an off-by-one error
count = 0; //reset count
}
if (index = arrayList.size()) {
index = 0; //reset index
}
}
}
So, you can see the trick is to think step by step what you're doing, and then slowly translate that into code. I think you may have been caught up on fixing your initial attempt: never be afraid to throw code out.
Try the following code. It keeps on removing every nth element in List until one element is left.
List<Integer> array = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
int nth = 3;
int step = nth - 1;
int benchmark = 0;
while (array.size() > 1) {
benchmark += step;
benchmark = benchmark > array.size() - 1 ? benchmark % array.size() : benchmark;
System.out.println(benchmark);
array.remove(array.get(benchmark));
System.out.println(array);
}
You could use a counter int k that you keep incrementing by three, like k += 3. However, before you use that counter as an index to kick out any array element, check if you already went beyond and if so, subtract the length of this array from your counter k. Also make sure, to break out of your loop once you find out the array has only one element left.
int k = -1;
int sz = list.length;
while (sz > 1)
{
k += 3;
if (k >= sz)
{
k -= sz;
}
list.remove(k);
sz --;
}
This examples shows that you already know right away how often you will evict an element, i.e. sz - 1 times.
By the way, sz % 3 has only three possible results, 0, 1, 2. With a piece of paper and a cup of coffee you can find out what the surviving element will be depending on that, without running any loop at all!
You could try using an iterator. It's late irl so don't expect too much.
public removeThirdIndex( listOfWords ) {
Iterator iterator = listOfWords.iterator
while( iterator.hasNext() ){
iterator.next();
iterator.next();
iterator.next();
iterator.remove();
}
}
#Test
public void tester(){
// JUnit test > main
List listOfWords = ... // Add a collection data structure with "words"
while( listOfWords.size() < 3 ) {
removeThirdIndex( listOfWords ); // collections are mutable ;(
}
assertTrue( listOfWords.size() < 3 );
}
I would simply set the removed to null and then skip nulls in the inner loop.
boolean continue;
do {
continue = false;
for( int i = 2; i < list.length; i += 3 ){
while( list.item(i++) == null && i < list.length );
Sout("Player " + list.item(--i) );
continue = true;
}
} while (continue);
I'd choose this over unjustified shuffling of the array.
(The i++ and --i might seem ugly and may be rewritten nicely.)

Categories