JavaArray Index out of Bounds exception w/ for loop - java

I am getting an array index out of bounds exception while iterating over an array through the for-loop. Can someone tell me why this is happening it I have set the boolean in the for-loop to be i
public static boolean verify(int [] seq ){
for (int i=0; i<seq.length; i++){
//If the number is even, the next number
//must the half the previous number
if (seq[i] %2==0){
if (seq[i+1] != (seq[i]/2)){
return false;
}
}
//If the number is positive, the next number
//must be 3 times + 1 the previous number
else if (seq[i] %2!=0){
if (seq[i+1] != ((seq[i])*3+1)){
return false;
}
}
}
}

The problem is when you access index i+1. If i is the last possible value (seq.length - 1), then i+1 is one beyond the end of the array, resulting in an ArrayIndexOutOfBoundsException.
Stop your for loop one iteration earlier by modifying your condition to be:
i < seq.length - 1

You will face exception for the maximum value of i bcoz you are increasing the value by 1 to find the index value.
if (seq[i] %2==0){
if (seq[i+1] != (seq[i]/2)){
---------------------^
return false;
}
}

You're trying to access position i+1 or the Array. Since your for loop goes until the last element, you'll try to access 1 position after the last element, what causes the Out Of Bounds exception.

You are iterating over all elements in the array, but checking element seq[i + 1] for i == seq.lenth - 1 will always cause the exception. The last number is fully constrained by your conditions, so no need to check it. Make your loop run as follows: for (int i=0; i <seq.length - 1; i++)

This:
if (seq[i+1] != (seq[i]/2)) {
cannot access an element beyond the end of the array, when i is seq.length - 1.
Another line like that is down in the else branch.

Its quite obvious , when you are passing an array (i.e. array contains 10 elements) and operating inside loop that correct.But when you are accessing seq[i+1] , there might be the you are accessing the index which is not available in the array.
When the i value reaches at 10 and you are trying to access i+1 , but this index is not in array (as we know array size is 10)
So , its caused this exception.
Hope it will help you.

Related

Which recursive method could be used to evaluate numbers in a list?

I'm strugling learning recursive methods. Could use some advice and a cheer-up :D
Lets say I have a set of numbers in an array, and I want to use a recursive method to evaluate numbers in this set, and by evaluation I mean that our program needs to find zeros in this set, and as a result it should print out position of the last zero in given array.
int a[] = {2,3,4,5,0,1,2,0,5,0};
In case if array above is being evaluated by a recursive method, the program will evaluate each number and, if zero is found, it will save it's position in a variable, AND THEN MOVE ON REPEATING ITSELF until the end of the array. So first zero is at "4" and so on, but the output will show only the poistion number of the last zero in given array.
I kind of got the first part of this code going, but my recursion stops as soon as it finds a zero and just gives out a boolean type variable.
public static boolean checkNum(int i) {
if (i < a.length) {
if (a[i] != 0)
return checkNum(i+1);
else return false;
}
return true;
}
this block of code checks numbers in our set and returns boolean type variable true in case if it never found any zeros.
next method may be similar, but I dont know how to store the position number as a variable with a possibility to print it out in the end of my program. Is there any way to get int i out of the recursive method when it's done repeating itself? Because as far as I understand it is the same as a position number in an array, which I need to print out.
You have two options. Either continue until the end of the list and then return the last index found ... or iterate backwards across your list and use your logic as-is.
You're currently iterating forward, so might as well cover that workflow first.
Since your goal is to figure out the position, your method needs to return an int, not a boolean.
Since you need to return the last index of a zero, that means you need to track the previously found index.
Since you want to iterate to the end of the list, your end condition needs to be a position < length check.
static int[] a; // some array we're checking
public static int checkNum(int index, int lastZero) {
// End condition. If we've finished iterating across the array, return the
// index of the last zero we found.
if (index >= a.length) {
return lastZero;
}
// Check if we've found a zero at the current position.
if (a[index] == 0) {
lastZero = index;
}
// Continue traversing the list.
return checkNum(index+1, lastZero);
}
You'd call this by passing in a negative number as your initial lastZero index:
int lastZeroIndex = checkNum(0, -1);
That way you know that if you end up with a positive number, you have found the last index. Otherwise if you're left with a negative number, there were no zeroes in the array.
A simpler method would simply be to iterate backwards over the array and stop as soon as you find a zero.
We still return an int instead of a boolean because we want to know the index.
Otherwise your method signature remains the same.
static int[] a; // some array we're checking
public static int checkNum(int index) {
// End condition. We've reached the beginning of the array and never found a zero.
// Return a -1 to indicate this.
if (index < 0) {
return -1;
}
// If index is >= a.length, we don't want an index out of bounds...
if (index >= a.length) {
return checkNum(a.length - 1);
}
// Check if we've found a zero at the current position. If we have, return
// the current index.
if (a[index] == 0) {
return index;
}
// Continue traversing the list backwards.
return checkNum(index-1);
}
You'd call this by passing a.length - 1 as your parameter. That's the last valid index in the array, so it's our starting point when we iterate backwards.
int lastZeroFound = checkNum(a.length - 1);
If lastZeroFound is negative (eg. -1), then you found no zeroes.

Why is my int[] array loop out of bounds?

Warning: I am very new to Java and programming in general. I'll try to be as clear as possible.
I am attempting to take a simple integer (inputnumber), convert it to a string (temp), create a new int[] array (numberarray), and loop through this int[] array, starting from the last digit, and print out the name of the digit.
I am rather sure that the conversion from integer to String to int[] array was functional due to Eclipse debugging, but am stumped as to why I am getting an ArrayOutOfBounds message from Eclipse for such a simple for loop. Any clues as to what I am doing wrong is appreciated.
String temp = inputnumber.toString();
int[] numberarray = new int[temp.length()];
for (int i=0;i<temp.length();i++) {
numberarray[i] = temp.charAt(i);
}
for (int i=temp.length();i>0;i--) {
if (numberarray[i]==1) System.out.print("one.");
if (numberarray[i]==2) System.out.print("two.");
if (numberarray[i]==3) System.out.print("three.");
if (numberarray[i]==4) System.out.print("four.");
if (numberarray[i]==5) System.out.print("five.");
if (numberarray[i]==6) System.out.print("six.");
if (numberarray[i]==7) System.out.print("seven.");
if (numberarray[i]==8) System.out.print("eight.");
if (numberarray[i]==9) System.out.print("nine.");
if (numberarray[i]==0) System.out.print("zero");
}
The Eclipse error message I am getting is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at jt.Intermediate8.main(Intermediate8.java:44)
Arrays are 0-indexed in Java. This means the last value is at index NUMBER_OF_ELEMENTS - 1
Therefore, in your for loop, you should change
int i=temp.length() // this is last index + 1 (since we are starting from 0)
To:
int i=temp.length() - 1 // this is last index
Also, as #brso05 said, don't forget to change your loop-ending condition to i>=0 since the last value going backwards will be at index 0.
Your for loop:
for (int i = temp.length(); i >= 0; i--)
You're starting the loop at temp.length(). That's not a valid index. Perhaps you want temp.length()-1?
You should be doing temp.length() - 1. The reason is that the array starts with index 0 not 1 so the last element in an array is stored at the length - 1. If there are 10 elements then 0-9 are your indexes. Also change i>0 to i>=0 if you want to hit all elements.
for (int i=(temp.length() - 1);i>=0;i--) {

checking if Index out of Range with array

I have written a program with a lot of operations on arrays. How I can check if I out of range with array, because I go Run Time Error at SPOJ.
Without knowing any more detailed context, the basic approach as outlined by Jon Skeet in the comments is something like the following:
if (index < 0 || index >= array.length) {
//Index Out Of Range
}
There is no code to refer and see if you have gone out of range. Maybe you want to post your code for reference.
As long as your index is not of negative value and 1 value under the length of your array, you will be within bounds of your array.
For example an array of length 10, you have to minus 1 and able to call indexes between 0 - 9.
for(int x=0; x < yourArray.length; x++){
//this for loop will nicely loop without going out of bounds unless your
//loop body contains something that will trigger the error.
}

bubble sort string array

I'm trying to use a bubble sort to alphabetize an array that I've read into a program. The code compiles without error but I get an Array Index Out Of Bounds Exception on my 'if' construct when I try to run the program. I have initialized int i to 0 to account for the first index of the array so I think my error is elsewhere. I'm not asking anyone to write code for me, just maybe a point in the right direction. Thanks for any help.
public static String[] bubbleSort(String[] inL)
{
String temp;
int i = 0, passNum;
for(passNum = 1; passNum <= (inL.length); i++) // controls passes through bubble sort
{
if(inL[i].compareToIgnoreCase(inL[i + 1]) < 0)
{
temp = inL[i];
inL[i] = inL[i + 1];
inL[i + 1] = temp;
}
}
return inL; // returns sorted array
} // end bubbleSort method
You compare passNum instead of i against the length of the array. Since passNum is never modified, the loop condition is always true, and i gets incremented until it exceeds the range of the array.
Even if this particular issue is resolved, you may still run into problems with off-by-one errors with your current implementation. Consider whether you should compare i against inL.length - 1.
You never increment passNum so i continues incrementing forever. Also, array indexing in Java is based at 0. That means that the largest valid index is inL.length - 1. Since the body of your loop accesses inL[i+1], you should arrange your code so that i never exceeds inL.length - 2. At a minimum, you should change <= to < in the for loop termination test. (However, the logic of your comparison and incrementing escapes me; you need to fix that as well.)
Array.length stores the total length of an array, starting counting at 1.
The first index in an array however is 0, meaning that the last index is length-1.
adjust your check in your for-loop to fix the error
Your problem is the passNum <= (inL.length) it should be passNum < (inL.length) due to 0 being the first index of an array in java

How to check ALL elements of a boolean array are true

I have a boolean array whose size depends on the size of a randomly selected string.
So I have something like this:
boolean[] foundLetterArray = new boolean[selectedWord.length()];
As the program progresses, this particular boolean array gets filled with true values for each element in the array. I just want to print a statement as soon as all the elements of the array are true. So I have tried:
if(foundLetterArray[selectedWord.length()]==true){
System.out.println("You have reached the end");
}
This gives me an out of bounds exception error. I have also tried contains() method but that ends the loop even if 1 element in the array is true. Do I need a for loop that iterates through all the elements of the array? How can I set a test condition in that?
Using the enhanced for loop, you can easily iterate over an array, no need for indexes and size calculations:
private static boolean allTrue (boolean[] values) {
for (boolean value : values) {
if (!value)
return false;
}
return true;
}
There is a Java 8 one-liner for this:
boolean allTrue(boolean[] arr) {
return IntStream.range(0, arr.length).allMatch(i -> arr[i]);
}
boolean[] foundLetterArray = new boolean[5];
The memory allocation for the abow array is like
foundLetterArray[0],foundLetterArray[1],foundLetterArray[2],foundLetterArray[3],foundLetterArray[4]
Array index starts with 0 and the total memory count is 5 and the last array index is 4.
You are trying to get index 5 that is foundLetterArray[5] which does not exist. That's why you are getting the ArrayIndexOutofBoundsException
if(foundLetterArray[selectedWord.length()-1]==true){
System.out.println("You have reached the end");
}
Arrays in Java starts from index 0 and last index is always [array.length()-1]
As you are checking for foundLetterArray[selectedWord.length()] ,its giving you a array out of Bound Exception try foundLetterArray[selectedWord.length()-1]
Like:
if(foundLetterArray[selectedWord.length()-1]){
System.out.println("You have reached the end");
}
Indices in java, as well as most programming languages, are 0-based, meaning that individual elements in an array with n elements have indices 0, 1, 2, ..., n-1. The last element in an array is always at index array.length - 1.
Array index start from 0 so last index is always 1 less then array length so here you are trying to access last index + 1 by doing foundLetterArray[selectedWord.length()] this so it is throuing ArrayIndexBoundEception use array.lastIndex() method or subtract 1 form length.
Implementing this foundLetterArray[selectedWord.length()-1] You must take care about one thing if your array does not contains any elements then selectedWord.length() return 0 and again you will get same exception so Its good to check lengh before doing this foundLetterArray[selectedWord.length()-1].
do this
public boolean allTrue(boolean[] array) {
for (boolean b : array) {
if (!b) {
return false;
}
}
return true;
}
There is no 'one line' way of knowing whether all of the elements of an array meet a certain condition (there are libraries that take care of the looping for you, but you still need to write the condition). Querying array[x] will only tell you about the xth item in that array, so for your question you need to check every item.
Also, as other people have pointed out, array indices are 0-based, so the first element is at array[0] and the last at array[array.length() - 1].
My example uses an alternate looping construct known as for-each. This is appropriate when you don't need to modify the array contents, you only need to read from them. It avoids any messing around with indices.
You do the check only for last element in the array ( and do it wrong, above is described why ).
In order to get if arrays contains only true values you should check all of them.
boolean allAreTrue = true;
for (boolean val : foundLetterArray) {
allAreTrue = allAreTrue && val;
}
// at this line allAreTrue will contain true if all values are true and false if you have at least one "false"

Categories