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++) .
Related
This question already has answers here:
Does a primitive array length reflect the allocated size or the number of assigned elements?
(17 answers)
What does arrays.length -1 mean in Java?
(1 answer)
How do you determine the legal index range for an array?
(1 answer)
Closed 5 years ago.
The community reviewed whether to reopen this question last month and left it closed:
Original close reason(s) were not resolved
class Zillion {
private int zilly[];
public Zillion(int size){
zilly = new int[size];
}
public void increment(){
int i=zilly.length -1;
while(i>=0){
if(zilly[i]!=9){
zilly[i]+=1;
i=-1;
}
else{
zilly[i]=0;
i--;
}
}
}
I just got a basic java code like this and do not know what length -1 means at this part (int i=zilly.length -1;).
Can someone please explain this ?
The size of array is the number of elements in this array, but The first index of arrays is 0. For example :
int zilly[] = {1, 2, 3, 4}
In this example :
zilly.size return : 4
But zilly[4] not exist because the index of the first element is 0
zilly.[zilly.size - 1] return the last element (4).
Hope it helps.
nameOfTable.lenght return the number of element
the first index of Arrays start with 0 ==> (1st - 1 = 0) ,
so the last index is n - 1
int i=zilly.length -1; is the last index of the array, because arrays start at index 0.
A side note, the formatting of this code be improved to better portray what it's doing, for example the line that confused you could be.
int i = zilly.length - 1; simply spacing out the statement correctly makes it a bit easier to understand.
zilly.length -1 defines itself. Total array length (size) -1.
Since the first index of array starts with 0 so the last item is at position n-1 where n is the size of array.
In Java indexing of arrays starts from 0. Therefore the last element of arrays is accessed by zilly[zilly.length - 1]. If you try to access it this way:
zilly[zilly.length]
you will get an out of bounds exception.
The while loop in your code starts from the last index and iterates down the very first element.
zilly.length gives the length of the array, i.e. the number of elements in it.
zilly.length-1 gives the last index of the array because the count of the array begins from 0.
So basically you are iterating in a descending order, i.e. from the last element of the array to the first element of the array.
It means that we want to get the last index in the array.
And then we loop over the array from end to start.
zilly.length it's the array size - but the array's index starts from 0 so the last index is zilly.length-1
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
Need help running this code, I need to find the error so I can fix it. Thanks!
the error receive is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at DebuggingExercise.main(DebuggingExercise.java:13)
import java.io.*;
public class DebuggingExercise {
public static void main(String[] args)
{
int[][] testArray = new int[5][6];
for(int i=0;i<5;i++)
{
for(int j=1; j<=6; j++)
testArray[i][j] = (i+1)*j;
}
}
}
Welcome to StackOverflow. Let's explain this step by step:
int[][] testArray = new int[5][6];
means a two dimensional array with 5 rows and 6 columns. Array's index start from 0. So 5 rows will be given indices like; 0,1,2,3,4
And each row will contain 6 columns that means, 0,1,2,3,4,5
for(int i=0;i<5;i++)
means start from 0 and go until 4 because when i's value becomes 5, this will finish this loop. That's okay, since you are using i to refer to the row index. So 0,1,2,3,4 for rows will be fine in this case.
for(int j=1; j<=6; j++)
That means, start from 1 and go until 6. Since you are referring the array's column with j, it will be like following when value of i is 0.
testArray[0][1]
testArray[0][2]
testArray[0][3]
testArray[0][4]
testArray[0][5]
testArray[0][6] //Here is the exception since each row has only 6 columns and array index starts with 0 that is: 0,1,2,3,4,5
Hence you receive ArrayIndexOutOfBoundException
In this for loop:
for(int j=1; j<=6; j++)
testArray[i][j] = (i+1)*j;
"6" is out of the index of the array of size "6" (0 - 5).
I'm a new to java.I'm looking to print the contents in the two dimmensional array namely myPoints.However,when i'm printing the code.it is throwing up the following error.
mypoints4
i value is 0
2
i value is 1
5
i value is 2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
2 at perceptron.main(perceptron.java:37)
import java.util.*;
import java.io.*;
import java.text.*;
import java.math.*;
import java.awt.*;
class perceptron{
public static void main(String[] args){
int[][] myPoints = {{2,3},{4,5},{7,8},{9,10}};
int [][] myplot = {{3,4},{5,6},{5,5},{5,3}};
int sum=0;
int i=0;
System.out.println("mypoints"+myPoints.length);
while(i<=myPoints.length){
System.out.println("i value is"+i);
System.out.println(myPoints[i][i]);
i = i+1;
}
}
}
You need to use nested loops for that.
The reason you get the ArrayIndexOutOfBoundsException is because you're using myPoints[i][i], so when i is 2 it is looking for the third element of the third inner array (ie {7,8}) when it doesn't exist
This is because of while(i<=myPoints.length) need to be while(i<myPoints.length).. In case of array in size 5, your i should be i=0, i=1, i=2, i=3, i=4.. Exclude 5.
Another issue is:
System.out.println(myPoints[i][i]);
should be : System.out.println(myPoints[i][0] + " " + myPoints[i][1]);
Because the second dimensional of youre array is only 2 size.. and not 5
Your condition on the while loop must be "less" not "less or equal".
This is because the array index is zero based and hence the index range is always from 0 to (length - 1).
You're going up to (and including) the length of the outer array. This is an array index out of bounds because the indices of an array of length n are 0 ... (n-1). So trying to access index n is out of bounds.
You're accessing the sub array at index i, which is out of bounds for later sub arrays. This would work for a square matrix (you'd read down the diagonal), but your matrix is 4*2, so myPoints[2][2] is OOB, because you can't access index 2 of the length 2 array {7,8}.
The simplest way to iterate over every element in a 2-D array is to have to have a nested loop, like such:
for(int i = 0; i < myPoints.length; i++){
for(int j = 0; j < myPoints[i].length; j++){
System.out.println(myPoints[i][j]);
}
}
An even more concise way of doing this is by using a for-each loop, which gets rid of indices entirely and just gives you each element in the array, in order:
for(int[] row : myPoints){
for(int val : row){
System.out.println(val);
}
}
An even more concise way is to use the method Arrays.deepToString(...):
System.out.println(Arrays.deepToString(myPoints));
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--) {
I get the output for the program mentioned below. In addition Ii also encounter an exception as:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at ReverseOrder.main(ReverseOrder.java:15)
Why does this happen?
public class ReverseOrder {
public static void main(String[] args)
{
int anArray[]={1,2,3,4,5,6};
int anotherArray[]=new int[6];
for(int i=5,j=0;i>=0;i--,j++)
{
anotherArray[j]=anArray[i];
}
//System.out.println(anotherArray.length);
//System.out.println(anotherArray[2]);
for(int j=0;j<=anotherArray.length;j++)
{
System.out.println(anotherArray[j]);
}
}
}
Change
for(int j=0;j<=anotherArray.length;j++)
to
for(int j=0;j<anotherArray.length;j++)
Since if it's <= you'll be going out of bounds.
In Java (and most languages), arrays are zero-based. If you have an array of size N then its indexes will be from 0 to N - 1 (total size of N).
The problem is here:
for(int j=0;j<=anotherArray.length;j++)
{
System.out.println(anotherArray[j]);
}
you are accessing a position out of the array. This happen because method length gives you the number of elements in the array, and since the first position of an array is 0 and not 1 you should end the loop on anotherArray.length - 1 and not anotherArray.length.
There are two possible solutions to this where you modify your loop to:
a) for(int j=0;j<=anotherArray.length - 1;j++)or
b)for(int j=0;j<anotherArray.length;j++)
The latter (b) is preferable, since it has less arithmetic operations on it.
change
<=anotherArray.length
to
< anotherArray.length
For example, if array is
int arr[] = new int[2];
arr.length; // it will be 2, which is [0] and [1] so you can't go upto <=length,
// that way you will access [2] which is invalid and so the exception
for(int j=0;j<anotherArray.length;j++)
instead of
for(int j=0;j<=anotherArray.length;j++)
Because arrays are zero-based in Java.
You will get ArrayIndexOutOfBoundsException when you try access the element that's out of Array limit.
for(int j=0;j<anotherArray.length;j++) {
System.out.println(anotherArray[j]);
}
Why do you use this way to reverse your array in first place. Any way
for(int j=0;j<=anotherArray.length;j++) should change to
for(int j=0;j<anotherArray.length;j++)
Consider this too, It is easy.
int anArray[]={1,2,3,4,5,6};
int temp=0;
for (int i=0;i<anArray.length/2;i++){
temp=anArray[i];
anArray[i]=anArray[anArray.length-(1+i)];
anArray[anArray.length-(1+i)]=temp;
}
Now your array is reversed.