ArrayIndexOutOfBounds Exception for some input values - java

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

Related

JAVA Writing the diagonal of an 2-dimensional array into an 1-dimensional array

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.

Beginner Looking for Guidance on Methods

I am trying to complete a project where we have to take a set of data of random numbers between 0 and 364 and see what percentage of the runs (the method takes the number of items in the data set and the number of runs) have a duplicate number in them.
Below is what I have so far, but I am really struggling to figure out how to do this as I keep getting errors:
public double calculate(int size, int count) {
double percentage;
int matches = 0;
int check;
int i = 0;
int add = 0;
Random rnd = new Random();
List<Integer> birthdays = new ArrayList<>();
for (int k = 1; k <= count; k++){
rnd.setSeed(k);
do{
add = rnd.nextInt(365);
birthdays.add(add);
i++;
}while (i < size-1);
//birthdays.add(rnd.nextInt());
for (int j = 0; j <= size-1; j++) {
check = birthdays.get(j);
if (birthdays.indexOf(check) != birthdays.lastIndexOf(check)) {
matches++;
j = size;
}
}
}
percentage = (double)matches / count * 100;
//percentage = 8;
return percentage;
}
There are a couple of problems with your code here. One is the while loop directly after the first for loop that doesn't seem to be doing anything. It says:
while(i < size-1);
That might be giving you an error, but error you are talking about is probably from your second for loop. When you instantiate it you say:
for (int j = 0; j <= size-1; j++)
but then you say:
j = size;
since when you instantiate it you say j<=size-1 but then you set j=size it will give an error.

ArrayIndexOutOfBoundsException 8 runtime exception in my array sorting code

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

How to compare two arrays of different sizes?

So my task is to read a file line by line and store the integers into an array. Then to add the integers in spots 1-5, 2-6, 3-7 etc. and store those into a new array.
In array 1 there is 4 more values than array 2. I need to compare these Arrays and see if array1 is 0.999 bigger than array2.
If it is indeed larger, I need to print out the LOCATION of the number in the array 1.
Right now my problem is my code is outputting that every number is larger than the corresponding number in array 2.
Code:
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class Asgn7
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner file = new Scanner(new File("asgn7data.txt"));
double[] array = new double[file.nextInt()];
double[] newArray = new double[array.length - 4];
double tempVal = 0;
int j = 0;
int count = 0;
while(file.hasNext())
{
for(int i = 0; i < array.length ; i++)
{
array[i] = file.nextInt();
}
for(j = 0; j < array.length - 4; j++)
{
for(int k = 0; k < 5; k++)
{
newArray[j] += array[j+k] / 5;
}
}
for(int i = 2; i < array.length; i++)
{
if(array[i] > (newArray[i-2] + 0.999));
{
count++;
tempVal = count;
}
System.out.println(tempVal);
}
}
}
}
The values which should be compared are from 3-13.
Judging by the picture, you are not placing the values in the correct index in the second array, or you are not matching the correct ones.
If you want it to look exactly like in the picture, the second array should be declared:
double[] newArray = new double[array.length - 2];
And the loop to fill it should be changed to:
for(j = 2; j < array.length - 2; j++)
{
for(int k = -2; k <= 2; k++)
{
newArray[j] += array[j+k] / 5;
}
}
This will put the averages in the third, fourth, fifth... elements in newArray. And now you can compare them directly:
for(int i = 2; i < array.length - 2; i++)
{
if(array[i] > (newArray[i] + 0.999))
{
count++;
tempVal = count;
}
System.out.println(tempVal);
}
If you want to save the two unused spaces, as you originally did, rather than responding exactly to the picture, then you should calculate the values as you originally did. But remember to compare each element to the one two places before it and stop 2 places before the end.
Instead of
for(int i = 2; i < array.length; i++)
use
for(int i = 2; i < array.length - 2; i++)
To print the location, your construct with the count and tempVal is unnecessary. You just need to print i+1. Also note that you have a ; after your if. This means it's an empty if, and the block after it is always performed. Never have a ; after an if, for, while etc.
Not clear with what you are asking for in your question but without questioning what's the logic, by just looking at your code:
for(int i = 2; i < array.length; i++)
{
if(array[i] > (newArray[i-2] + 0.999));
{
count++;
tempVal = count;
}
System.out.println(tempVal);
}
}
if you relocate the system.out line as follows, I think you will get what you expect as follows:
for(int i = 2; i < array.length - 2; i++)
{
if(array[i] > (newArray[i-2] + 0.999));
{
System.out.println(tempVal);
// count++;
// tempVal = count;
}
}
}
PS: Please note that I have also changed the boundary for the loop to stop iteration on 13th member of the array, instead of 15.
Are you sure you're parsing the numbers correctly?
See Java: Reading integers from a file into an array
Why don't you print them out after parsing for verification?
btw, this will overflow the index of the 2nd array (since it is created using new double[array.length - 4]):
for(int i = 2; i < array.length; i++)
so does your code run?

Sieve of Eratosthenes, ArrayIndexOutOfBoundsException, output is composite number

I tried writing a Sieve of Eratosthenes algorithm, I am getting an ArrayIndexOutOfBoundsException but I don't seem to understand why, if I change the limits, upon printing it only displays composite numbers, the code's below help if you can.
public static Boolean[] solution(int N) {
Boolean[] isPrime = new Boolean[N];
isPrime[0] = false;
for(int i = 1; i <= N; i++) {
isPrime[i] = true;
}
for(int i = 2; i <= N; i++) {
if(isPrime[i]== true) {
System.out.println(i);
for(int j = 2; (j * i) < N; j++) {
int k = j * i;
isPrime[k] = false;
}
}
}
return isPrime;
i <= N; cause the error
for(int i = 1; i <= N; i++) {
isPrime[i] = true;
}
for example
if N=4 then you get error when i=4. isPrime[4] cause OutOfBounds exception because length is 4.arrays are zero index based. so maximum index you can access is 3.isPrime[3]
you can avoid this error by changing loop to for(int i = 1; i < N; i++) {
however i'm not sure what is Eratosthenes algorithem is .i hope you can change your code keep in mind arrays are zero index based
Boolean[N] creates an array of N elements, so, since the indexes start from 0, the last index is N-1.
The error is caused by i<=N in the for loop

Categories