I was trying to create an array sorting program in Java. So I created this method and tried to execute it by calling it from another function . But I am getting this "ArrayIndexOutOfBoundsException 8" runtime exception. So how do I fix it?
class arrayfunc {
int[] ascend(int[] p) {
int x = p.length;
for (int i = 0; i <= (x - 1); i++) {
int l = p[i];
for (int j = i + 1; j <= x; j++) {
int f = p[j];
if (f > l) {
int k = p[i];
p[i] = p[j];
p[j] = k;
}
}
}
return p;
}
}
Your inner loop
for(int j=i+1;j<=(x);j++)
should probably be
for(int j=i+1;j<=(x-1);j++)
otherwise you will get an ArrayIndexOutOfBoundsException here:
int f=p[j];
when your index variable j reaches the value of x
Replace <= by < in both your for loops.
By the way, Java will never win a code golf. You can expand your text...
Related
Want to write the diagonal of an 2-dimensional array (n*n Matrix) into an one-dimensional array.
1 2 3
4 5 6 => 1 5 9
7 8 9
public int[] getDiagonalFromArray(int[][] two_d_array){
int[] diagonal_array = new int[two_d_array[0].length];
int k=0;
for (int i = 0; i < two_d_array[0].length; i++) {
for (int j = 0; j < two_d_array[1].length; j++) {
for (int l = 0; l < two_d_array[0].length; l++) {
diagonal_array[k]=two_d_array[i][j];} //HERE SHOULD BE THE ERROR... HOW DO I CYCLE THROUGH THE 1dim "diagonal_array"?
}
}
return diagonal_array;
}
This method delivers wrong values.
This method of mine works, but just Prints the diagonale, instead of putting it into an 1dim array.
public void getDiagonal(int[][] two_d_array){
//int[] diagonal_array = new int[two_d_array[0].length];
for (int i = 0; i < two_d_array[0].length; i++) {
for (int j = 0; j < two_d_array[1].length; j++) {
if (i==j) System.out.print(two_d_array[i][j]+" ");
}
}
}
Where is the logical difference? I tried the if-clause on the first method, but it raises the "outofbound"-Exception.
Thanks in advance.
Why do you need more than one loop?
for (int i = 0; i < two_d_array[0].length; i++) {
diagonal_array[i]=two_d_array[i][i];
}
Seems to be enough to me.
If your matrix has the same width and height, this is a solution:
public int[] getDiagonal(int[][] two_d_array){
int[] diagonal_array = new int[two_d_array.length];
for (int i = 0; i < two_d_array.length; i++) {
diagonal_array[i] = two_d_array[i][i];
}
return diagonal_array;
Here, I consider principal diagonal elements to be the set of elements , where n & m are the number of rows and the number of columns (per row?) respectively.
Thus, the number of diagonal elements is never greater than min(numOfRows, numOfColumns).
And so, you can always try:
public int[] getDiagonalFromArray(int[][] 2DArray){
int[] diagonalArray = new int[Math.min(2DArray.length, 2DArray[0].length]);
int k=0;
for (int i = 0; i < 2DArray.length && k < diagonalArray.l length; ++i) {
for (int j = 0; j < 2DArray[i].length && k < diagonalArray.l length; ++j) {
if (i == j) {
diagonalArray[k++]=2DArray[i][j];
}
}
}
return diagonalArray;
}
Threw in some bounds checks for good measure.
Your input matrix must at be at least rectangular (square makes most sense), otherwise, the code will behave unreliably.
This is the same as #Andreas' answer, but I sacrifice performance and brevity here for the sake of understanding.
I am a student in a beginning java class, I got some help earlier today on my assignment, which really helped! So I thought I would give it one more try, before I throw in the towel on this last part. I have been able to get everything going, but my sort just doesn't work. I have to use this format, as my professor does not want us to use sort APIs. It processes correctly, meaning I get the same results by hand as when I run it, so I think the problem is in the logic itself. Can anyone see what I am doing wrong and offer any hints or helps. Thanks in advance. Here is my code for my sort loop:
int i, j; // used to index into the array
double temp;
for (i = 1; i < count ; ++i) {
temp = students[i].getGPA();
j = i - 1;
while (j >= 0 && temp < students[j].getGPA())
{
students[j + 1] = students[j];
j = j - 1;
}
students[j + 1]= students[i];
}
Your are not doing the swapping correctly. Check this sample code:
for (int i = 0; i < students.length; i++)
{
for (int j = 1; j < students.length - i; j++)
{
if (students[j - 1].getGPA() > students[j].getGPA())
{
// assuming that your class name is Student
Student temp = students[j - 1];
students[j - 1] = students[j];
students[j] = temp;
}
}
}
Your problem is that the first iteration through the while loop overwrites students[i]. You need to keep students[i], and not just its GPA, in a temporary value when you enter the for loop.
Refined your logic little bit. Plz verify for appropriateness!
package com.kvvssut.misc;
public class SortArray {
public static void main(String[] args) {
double [] studentsGPA = {8.3,7.2,10,6.5,4.9};
int count = studentsGPA.length;
int i, j; // used to index into the array
double temp;
for (i = 1; i < count ; ++i) {
j = i;
while (j > 0 && (temp = studentsGPA[j]) < studentsGPA[--j]) { // can use students[j].getGPA() similarly
studentsGPA[j+1] = studentsGPA[j];
studentsGPA[j] = temp;
}
}
for (double sgpa : studentsGPA ) {
System.out.println(sgpa);
}
}
}
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 try to create a program which computes image histogram. I ve got the above code but i cant figure out why it doesnt work.
public void hist(List<Integer> r, List g, List b){
int count[] = new int [256];
int rSize = r.size();
int gSize = g.size();
int bSize = b.size();
for (int j = 0; j<=255; j++){
for(int i = 0; i < rSize; i++){
if( r.get(i) == j ){}
//System.out.println(r.get(i) == j);
count[j]++;
}
}
for (int i = 0; i < count.length; i++) {
System.out.print(count[i]);
}
}
If i call it in main, every element of count is rSize which is impossible as r list has the values of Red channel of an image.
Your if is empty: if( r.get(i) == j ){}.
It should be:
if( r.get(i) == j )
{
count[j]++;
}
Might want to use the debugger next time and simply step through your code, would've caught this easily.
To add to the previous answers that your if is empty (auto formatting in your IDE would show that your indentation is incorrect).
However, there is no need to have nested loops. If r can have any Integer or null, then you can have:
for (Integer integer: r){
if (integer != null) {
int i = integer;
if(i >= 0 && i<= 255) {
count[i]++;
}
}
}
and assuming r only contains integers that fit in count, then you can have
for (int i: r){
count[i]++;
}
Hi I am trying to take two arrays and turn them into one 2 dimensional array. However, I keep getting an error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at test5.sum(test5.java:12)
at test5.main(test5.java:38)
Here is my code:
public class test5 {
int[][] final23;
public int[][] sum(int[] x, int[] y) {
final23 = new int[2][x.length];
for (int i = 0; i < final23[i].length; i++) {
final23[1][i] = x[i];
final23[2][i] = y[i];
}
return final23;
}
public void print() {
for (int i = 0; i < final23[i].length; i++) {
for (int j = 0; j < final23[i].length; j++) {
System.out.print(final23[i][j] + " ");
}
}
}
public static void main(String[] args) {
int l[] = { 7, 7, 3 };
int k[] = { 4, 6, 2 };
test5 X = new test5();
X.sum(k, l);
X.print();
}
}
I am not really sure what the problem is. Sorry if the question is dumb, I am new to coding!
The problem is:
final23 [2][i] = y[i];
Java arrays always start at 0. So final23 only has [0] and [1].
Any array with n elements can go from 0 to n-1.
There is also a second problem with your program. You have this loop in both sum and print methods:
for (int i = 0; i < final23[i].length; i++)
In sum method it should be
for (int i = 0; i < final23[0].length; i++)
And in print method
for (int i = 0; i < final23.length; i++)
Otherwise you'll get ArrayIndexOutOfBoundsException again.
Note that the program works correctly only if both input arrays have the same length. This might be ok for your purposes, but keep that in mind.
Try
for (int i = 0; i < final23[i].length; i++)
{
final23 [0][i] = x[i];
final23 [1][i] = y[i];
}
Remember, all arrays are 0 based, even n-dimensional ones.