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

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--) {

Related

How to make a loop to insert item in between all elements of an array

I have an an array [1,1,1,1,1,1] and I want to make a for loop that will insert a 0 in between all the 1s.
I’ve tried using
for(int i=0;i<array.length;i+2) {
insertItem(array,i,0);
}
But this doesn’t work since the array increases in length every time you insert an item, and my client crashes.
Create a new array that is twice the length of the input, then loop through your input array and for each element, add it to the new array followed by a 0 updating an index as you go so that you are putting your 1s and 0s in the right position.
Not sure if you want a 0 at the end, if not adjust the details above accordingly (eg new array is twice size of input minus 1)
I'm assuming insertItem increases the length of array as needed. In that case the trick is to calculate the number of new insertions required (array.length - 1) before starting the loop. New values are inserted at odd locations, given by 2*i+1
int n = array.length - 1;
for(int i=0; i<n; i++) {
insertItem(array, 2*i+1, 0);
}
An alternative would be to create a new array and populate it like this:
int[] narr = new int[2*arr.length-1];
for(int i=0; i<narr.length; i++) {
narr[i] = (i % 2 == 0) ? arr[i/2] : val;
}
I think you just created an infinite loop. In your for loop, the i+2 should be replaced by i+=2. If not, the condition will never be met.

String index out of bound [duplicate]

This question already has answers here:
String index out of bounds exception java
(3 answers)
Closed 6 years ago.
int b[]=new int[s.length()];
for(int r=0;r<=s.length();r++)
{
b[r]=(int) s.charAt(r);
b[r]=b[r]+2;
}
I am getting a string index out of bounds error in line 4. Everything seems to be right. What's going wrong?
Change the loop logic a little
int b[]=new int[s.length()];
for(int r=0;r<s.length();r++)
{
b[r]=(int) s.charAt(r);
b[r]=b[r]+2;
}
Notice that loop should run upto r < s.length()
The problem is that at the end of the loop the value of r is greater than the maximum index of this array by 1 and thus the s.charAt() is causing an error.
use :
int b[]=new int[s.length()];
for(int r=0;r<=s.length()-1 ;r++)
{
b[r]=(int) s.charAt(r);
b[r]=b[r]+2;
}
because Array's index starts from 0,hence your iteration must run length-1
dont forget array starts with 0 and
array size or length starts with 1.
the problem is somewhere in for loop.
You dont normally loop an array like this:
for(int r=0;r<=s.length();r++)
just because the arrays are null index objects, i.e.
you can elements located in a range between 0 and length-1
[0,length)
i.e doing
for(int r=0; r<s.length(); r++)
now, you are trying to get the element #length and that is the reason of the exception
Yes you will get because strings indexstart from 0 and goes upto (string length -1) .
Suppose
String str=new String("Graceful")
then
str.charAt(0)==G and str.charAt(7)==l , so now what you are doing is to access element at charAt(8)==XXX which contains nothing and you are getting string index out of bound .
MySolution What you can do is change code
for(int r=0;r<str.length();r++)
or
for(int r=0;r<=str.length()-1;r++) .

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.
}

JavaArray Index out of Bounds exception w/ for loop

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.

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

Categories