This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
When the below method is run it throws an ArrayIndexOutOfBoundsException at line 179, which is the if statement in the nested loop.
I was thinking it had something to do with the index of j-1. So I took the -1 out and just had j in the brackets, but it threw the same exception at the first line of the swap. I've looked for bubble sort syntax and from what I can tell is I'm good. I'm close, I know. Any suggestions to fix this?
public static void bubbleSort(int[]array1){
int temp = 0;
for(int i = 0; i < array1.length; i++){
for(int j = 0; j < (array1.length - i); j++){
if(array1[j-1] > array1[j]){
//swap
temp = array1[j-1];
array1[j-1] = array1[j];
array1[j] = temp;
}
}
}
}
The only problem because of which you are getting this error is the case when j = 0, because at that time j-1 = -1. Which is not a valid index value in java and hence arrayIndexOutOfBounds exception. I have made the necessary change in the code. Have a look in the snippet below.
public static void bubbleSort(int[]array1){
int temp = 0;
for(int i = 0; i < array1.length; i++){
for(int j = 0; j < (array1.length - i-1); j++){
if(array1[j] > array1[j+1]){
//sawp
temp = array1[j];
array1[j] = array1[j+1];
array1[j+1] = temp;
The first element of the array is 0. With j-1 you get -1 and this is not in the range of the array.
You tried to put just "j". But, I think that you put "j+1" to compare. And the arrayIndexOutOfBounds exception was throwed because of the "j+1".
Try to use this at the second loop:
(array1.length - i - 1)
You are getting this exception because you have initiated j=0 and doing j-1. In that case it is going out of bound and hence giving exception. Code below will work fine.
public static void bubbleSort(int[] array1){
int temp = 0;
for(int i = 0; i < array1.length; i++){
for(int j = 1; j < array1.length-i; j++){
if(array1[j-1] > array1[j]){
//sawp
temp = array1[j-1];
array1[j-1] = array1[j];
array1[j] = temp;
}
}
}
For first iteration of inner loop when j=0, j-1 becomes -1 and arr[-1] is index out of bound exception.
Now when you change j-1 to j in if condition
if(array1[j-1] > array1[j]) // j-1 to j
Still in the first line swap arr[j-1] is arr[-1] which throws index out of bound exception.
Please follow the below code to avoid index out of bound exception.
Start j's iteration from 1.
`public static void bubbleSort(int[]array1){
int temp = 0;
for(int i = 0; i < array1.length; i++){
for(int j = 1; j < (array1.length - i); j++){ //initialize j=1 instead 0
if(array1[j-1] > array1[j]){
//sawp
temp = array1[j-1];
array1[j-1] = array1[j];
array1[j] = temp;
}
}
}
}`
Related
I read such a solution to rotate an array
the question:
public class Solution {
public void rotate(int[] nums, int k) {
int temp, previous;
for (int i = 0; i < k; i++) {
previous = nums[nums.length - 1];
for (int j = 0; j < nums.length; j++) {
temp = nums[j];
nums[j] = previous;
previous = temp;
}
}
}
}
I am confused about previous = nums[num.lengh -1],
is it a range as nums[0:10] or a single element as nums[0]?
It's a single element, he is taking the element in the num.length -1 position, and the value inside is being swapped with nums[j]:
for j=0 you have:
temp = num[0];
num[0] = num[num.length-1]
num[num.length-1] = temp;
And so on.
It is a single element, because num.lengh - 1 is an int and just gives you the last accessible index of the array.
If you check wether the length of the array is > 0, then you can safely use the length of the array to determine the last accessible index.
The length of an array is very often used in loops like yours:
Here the length is used to make sure you don't access unavailable indexes:
for (int j = 0; j < nums.length; j++)
You can write slightly a different condition without changing the functionality
for (int j = 0; j <= nums.length - 1; j++)
But if you do the following, you will get an IndexOutOfBoundsException:
for (int j = 0; j <= nums.length; j++)
The last iteration would try to access nums[nums.length], which isn't there...
nums[nums.length - 1]; gives you the last position of the array. It is -1 cause the positions of an array starts with 0 not with 1.
If you don't write -1 you would get an Out of bounds exception.
single, this is due to you're performing a mathematical expression and then getting a valeu from that. meaning you're taking the length of the array list then subtracting 1 and then getting that value or in other words you're getting the last value.
to get all values you must loop like a for loop etc.
for (i = 0; i < array.length; i++) {
System.out.print(array[i]);
}
I am not sure why I get this error and do not know how to solve it. I am getting a Runtime Exception:
for(int j = 0; j < instances[maxInstance].length; j++){
centroids[orphanCentroid][j]=instances[maxInstance][j];
}
for(int j = 0; j < instances[maxInstance].length; j++){
{
double temp = centroids[maxInstance][j] ;
centroids[maxInstance][j] = centroids[orphanCentroid][j] ;
centroids[orphanCentroid][j] = temp ;
}
Error is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at kmeans.KMeans.cluster(KMeans.java:75)
at kmeans.HW1.main(HW1.java:36)
And it happens at this line:
double temp = centroids[maxInstance][j] ;
I think you need
for(int j = 0; j < centroids[maxInstance].length; j++){
}
on your second for loop.
This can go either way, without additional information I can't really tell which one is out of bounds.
Case 1: centroids.length < maxInstance
In that case you simply can't access centroids[maxInstance], If you define them as
instances[10];
centroids[5];
int maxInstance = 5;
Potential solution: Check the size of instances.length and make sure centroids.length <= instances.length
Case 2: index j is out of bounds
Assuming centroids.length <= instances.length is true. Then
you need to check whether instances[maxInstance].length > centroids[maxInstance].length
Imaging where you define them as
new instances[maxInstance][10];
new centroids[maxInstance][5];
Then you will get java.lang.ArrayIndexOutOfBoundsException: 5 when you try to access
j=5;
centroids[maxInstance][5]
Potential solution:
for(int j = 0; j < centroids[maxInstance].length; j++){ //replace with centroids
The following is a part of my code.
For some values of bands and bandRows the code seems to run perfectly alright. But for some it gives an ArrayIndexOutOfBounds exception.
Any ideas where I might have gone wrong? I cannot find any mistake in the code.
Thanks in advance
for(int i=0; i<bands; i++)
{
int a=0;
while(a<bucketSize)
{
bandBuckets[i][a] = new ArrayList();
a++;
}
}
for (int i = 0; i < bands; i++)
{
for (int j = 0; j < preprocessedList.size(); j++)
{
int[][] forBuckets = new int[bands][bandRows];
for (int k = 0; k < bandRows; k++)
{
Arrays.fill(forBuckets[i], Bands[i][k][j]);
}
bandBuckets[i][h.hashBands(forBuckets[i], bucketSize)].add(j);
}
}
Here's the h.hashBands() function which is in another class
public int hashBands(int[] in, int bucketSize)
{
int hashVal = 0;
int k = in.length;
int base = 3;
for (int i = 0; i < in.length; i++) {
// for (int j = 0; i < in[i].length; i++)
hashVal += in[i] * Math.pow(base, k - i - 1);
}
return hashVal % bucketSize;
}
Perhaps there is an overflow in your hashBands() function.
The max value for an int is 231 - 1. hashVal will overflow when k - i - 1 is greater than 19. In Java, exceptions aren't thrown for overflows and underflows. Consider using a BigInteger and its modPow() function.
Can you tell where exactly you are getting ArrayIndexOutOfBoundException.
Seeing your code it seems that there might be some problem while returning from hashBands() function. It might be returning something greater than expected.
bandBuckets[i][h.hashBands(forBuckets[i], bucketSize)]
For the 2nd dimension of this array h.hashBands(forBuckets[i], bucketSize) --> this value might be greater than the expected value for that part.....
i have a problem that return me the follow error
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 1
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
at graphsshahar.TestDijkstra.main(TestDijkstra.java:38)
my program get a list of objects and i need to find in the list the equal to one
and then print it , here is the code
public static void main (String [] args){
System.out.println("begin");
int one = 2;
int two = 10;
List<Conniction> tempDeal = ConnictionDAO.getInstance().findPath(one, two);
List<String> oneid = new ArrayList<String>();
List<String> twoid = new ArrayList<String>();
for (int j = 1; j <= tempDeal.size(); j++) {
System.out.println("get");
if( Integer.parseInt(tempDeal.get(j).getOneid()) == one )
{
oneid.add(tempDeal.get(j).getOneid());
System.out.println(oneid.get(j));
}
}
System.out.println("end");
what should i fix ?
i dont know what is wrong with the if statement
Just change yours with this j < tempDeal.size() Numbering starts from 0 not from 1.
for (int j = 0; j < tempDeal.size(); j++) { ... }
If you would use j = 1 you are not able to get item at 0 position.
Update:
You can use also iterator like meant #AVD.
for(Conniction member: tempDeal) {
// do work
}
for (int j = 1; j < tempDeal.size(); j++)
If it is not intentional, 'j' should start from '0'
for (int j = 0; j < tempDeal.size(); j++)
List index starts with '0'
If index isn't matter then you may use iterator for loop.
for(Conniction obj: tempDeal){
if(obj!=null) {
if(Integer.parseInt(obj.getOneid())==one){
oneid.add(obj.getOneid());
}
}
}
Change this :
for (int j = 0; j < tempDeal.size(); j++) {
Lists indexes starts at 0 and ends at size() - 1
you need different counter for the oneid array. If the if-statement return false once, the next time you enter here you'll get IndexOutOfBounds.
int oneIdCount = 0;
and increment it inside the if
if( Integer.parseInt(tempDeal.get(j).getOneid()) == one )
{
oneid.add(tempDeal.get(j).getOneid());
System.out.println(oneid.get(oneIdCount));
oneIdCount++;
}
and as the above answers - start the for from int j=0
And if you want to print the last element only you can use oneid.size()-1 instead of variables.
I am new to Java, please help me.
My program is
import java.util.*;
import java.lang.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("a");
al.add("b");
for(int i=1;i<=10;i++)
{
al.add(i);
}
al.remove("a");
al.set(1,"c");
for(int j=3;j<=al.size();j++)
{
al.set(j,"z");
}
System.out.println(al);
}
};
in above any mistake........plz help me
a) You need to make the class public to run it:
public class Test
{
b) the last semi-colon is a syntax error No it's not, it's just unnecessary noise.
c) This fails with an IndexOutOfBoundsException:
for(int j = 3; j <= al.size(); j++){
al.set(j, "z");
}
It needs to be:
for(int j = 3; j < al.size(); j++){
al.set(j, "z");
}
Explanation: List Indexes are zero-based, so the highest position in a List with n elements is n-1
BTW, the above code can be written in a more elegant way like this:
Collections.fill(al.subList(3, al.size()), "z");
Reference:
Collections.fill(List<T>, T)
List.subList(from, to)
This code will throw an IndexOutOfBounds exception because of the line:
for (int j = 3; j <= al.size(); j++) {
to fix it, you need to change it to:
for (int j = 3; j < al.size(); j++) {
This is because the <= means that your for loop iterates over the end of the list.
List~ and Arrayindices start at 0, not 1. So if you have a list of 3 Elements, they go from index: 0, 1, 2. So you normally iterate from (i = 0; i < list.size (); ++i). Less than, not less/equal.
for (int j=3; j < al.size (); j++)
1.The semicolon in the last line
2.change the code from
for(int j=3;j<=al.size();j++)
to
for(int j=3;j<al.size();j++)
Arraylist are always accessed from from 0th index to less than the size of the array.
I think it is necessary to change also the start index from 3 to 2:
for (int j=2; j < al.size (); j++)