I'm trying to run a method that calls my class method below. Everytime I call the method computeIterative(), I get an ArrayIndexOutOfBoundsException. I added some code to print out the loop, and I see that the exception occurs around the second time through the loop, but the loop continues until complete. What am I doing wrong that I can't solve this array exception?
static int computeIterative(int n) {
efficiency = 0;
int[] a = new int[n];
int firstInt = 0;
int secondInt = 1;
int results = 0;
if (n > 1) {
a[0] = 0;
a[1] = 1;
for (int i = 2; i <= n; ++i) {
efficiency++;
firstInt = a[i-1];
secondInt = a[i-2];
results = 2 * firstInt + secondInt;
System.out.println("Loop " + efficiency + " of " + n );
System.out.println(firstInt);
System.out.println(secondInt);
System.out.println("Results: " + results);
a[i] = results;
}
} else {
a[0] = 0;
a[1] = 1;
}
return a[n];
}
Thank you for the help.
the error lies in the line
a[i] = results;
since in your for loop, you have been using :
for(i=2;i<=n;i++)
You will find that the array index starts from 0 and goes up to n-1. So when you are using :
i <= n
you will encounter an array out of bounds exception because it does not have a 'n'th element.
Change your for loop condition from :
i <= n
to :
i < n
and your code should work.
You have initiated array with size "n", you are trying to access a[n] element, array index starts from 0 to n-1.So when you access a[n] you are getting Arrayindexboundexception.
change this line from
int[] a = new int[n]; to int[] a = new int[n+1]; (line 3)
Works!!
If n is 2, you access a[2] (a[i] = results;) but there are only element 0 and 1
Related
Why is is giving me ArrayIndexOutOfBoundsException in second For loop?
public class Ass1Ques2 {
void rotate() {
int[] a = {3, 8, 9, 7, 6};
int r = 2;
int[] t1 = new int[(a.length - r) + 1];
int[] t2 = new int[r + 1];
for (int y = 0; y <= r; y++) {
t2[y] = a[y];
}
// This loop is giving error
for (int i = 0; i <= a.length - r; i++) {
t1[i] = a[i + r];
}
for (int f = 0; f <= t1.length; f++) {
System.out.println(t1[f] + " ");
}
for (int n = 0; n <= t2.length; n++) {
System.out.println(t2[n] + " ");
}
}
public static void main(String[] args) {
Ass1Ques2 r = new Ass1Ques2();
r.rotate();
}
}
I don't know how to fix this error,i think i have given the right length to t2.
I want to internally rotate the array clockwise according to r.
You access a[i+r], consider the last iteration of the loop. i = a.length-r so i+r = a.length-r + r = a.length which is out of bounds.
If you want to rotate the array, I recommend using the modulo (%) operator to compute the new position of an index. So in practice, add the rotation to all indices and modulo over the length of the array to get the new positions.
At the last iteration of the loop, you will be accessing a.length, which returns the entire length of the array starting at 1; which causes an IndexOutOfBounds exception since indices start at 0. In order to fix this, just do:
for (int i = 0; i < a.length - r; i++) {
t1[i] = a[i + r];
}
This will prevent the for loop from iterating to the very last spot of the array with an equal sign, which would've caused an IndexOutOfBounds exception.
So I have a problem, this method is supposed to sort an array of integers by using counting sort. The problem is that the resulting array has one extra element, zero. If the original array had a zero element (or several) it's fine, but if the original array didn't have any zero elements the result starts from zero anyway.
e.g. int input[] = { 2, 1, 4 }; result -> Sorted Array : [0, 1, 2, 4]
Why would this be happening?
public class CauntingSort {
public static int max(int[] A)
{
int maxValue = A[0];
for(int i = 0; i < A.length; i++)
if(maxValue < A[i])
maxValue = A[i];
return maxValue;
}
public static int[] createCountersArray(int[] A)
{
int maxValue = max(A) + 1;
int[] Result = new int[A.length + 1];
int[] Count = new int[maxValue];
for (int i = 0; i < A.length; i++) {
int x = Count[A[i]];
x++;
Count[A[i]] = x;
}
for (int i = 1; i < Count.length; i++) {
Count[i] = Count[i] + Count[i - 1];
}
for (int i = A.length -1; i >= 0; i--) {
int x = Count[A[i]];
Result[x] = A[i];
x--;
Count[A[i]] = x;
}
return Result;
}
}
You are using int[] Result = new int[A.length + 1]; which makes the array one position larger. But if you avoid it, you'll have an IndexOutOfBounds exception because you're supposed to do x-- before using x to access the array, so your code should change to something like:
public static int[] createCountersArray(int[] A)
{
int maxValue = max(A) + 1;
int[] Result = new int[A.length];
int[] Count = new int[maxValue];
for (int i = 0; i < A.length; i++) {
int x = Count[A[i]];
x++;
Count[A[i]] = x;
}
for (int i = 1; i < Count.length; i++) {
Count[i] = Count[i] + Count[i - 1];
}
for (int i = A.length -1; i >= 0; i--) {
int x = Count[A[i]];
x--;
Result[x] = A[i];
Count[A[i]] = x;
}
return Result;
}
Here you go: tio.run
int maxValue = max(A) + 1;
Returns the highest value of A + 1, so your new array with new int[maxValue] will be of size = 5;
The array Result is of the lenght A.lenght + 1, that is 4 + 1 = 5;
The first 0 is a predefinied value of int if it is a ? extends Object it would be null.
The leading 0 in your result is the initial value assigned to that element when the array is instantiated. That initial value is never modified because your loop that fills the result writes only to elements that correspond to a positive number of cumulative counts.
For example, consider sorting a one-element array. The Count for that element will be 1, so you will write the element's value at index 1 of the result array, leaving index 0 untouched.
Basically, then, this is an off-by-one error. You could fix it by changing
Result[x] = A[i];
to
Result[x - 1] = A[i];
HOWEVER, part of the problem here is that the buggy part of the routine is difficult to follow or analyze (for a human). No doubt it is comparatively efficient; nevertheless, fast, broken code is not better than slow, working code. Here's an alternative that is easier to reason about:
int nextResult = 0;
for (int i = 0; i < Count.length; i++) {
for (int j = 0; j < Count[i]; j++) {
Result[nextResult] = i;
nextResult++;
}
}
Of course, you'll also want to avoid declaring the Result array larger than array A.
I am practicing creating a randomly generating integers in an array, then randomizing the elements in the array. All is well when I print the numbers, but there seems to be one element that does not print when I am displaying the randomized elements. Is there a step I am leaving out?
public class shufflingArrays {
public static void main(String[] args) {
int[] myList = new int[10];
System.out.println("Numbers:");
for(int i = 0; i < myList.length; i++) {
myList[i] = (int)(Math.random() * 100);
System.out.print(myList[i] + " ");
}
System.out.println("\nRandomized:");
for (int i = myList.length - 1; i > 0; i--){
//Generate index j randomly with 0 <= j <= i
int j = (int)(Math.random() * (i + 1));
//Swap myList[i]; with myList[j]
int temp = myList[i];
myList[i] = myList[j];
myList[j] = temp;
System.out.print(myList[i] + " ");
}
}
Your for loop has condition i > 0, which means when i == 0 it will terminate and not print out the first array element.
However, if you're doing the Fisher-Yates shuffle, as it appears, you do indeed need to go from myList.length-1 to 1, so your initial code was correct. You then can't print out all the elements in the array from the same loop, so either use another loop after to print out the elements, or add System.out.print(myList[0]); after.
Ex: for (int i = 4; i > 0; i--)
will run the for loop when i = 4, 3, 2, 1 only and not when i = 0, because the condition there is i > 0. Change the i > 0 condition in for (int i = myList.length - 1; i > 0; i--) to i >= 0 and you will get what you want.
I'm writing a program to calculate the Hamming code, and I receive an array out of bounds exception. The issue seems to be with this method:
static int[] computeParityBits(int[] inWord, int[] parityBits) {
for (int i=0, m=2; m < inWord.length; i++) {
m = (int) Math.pow(m, i);
parityBits[i] = processPower(m, inWord);
}
return parityBits;
The integer m does not change it's value when using the Math.pow function on it. I've tried different things but I can't seem to make it work properly. The method is supposed to go through all powers of 2 as long as their value is lower than int[] inWord.length. After this it should assign parityBits[i] the value returned by the method processPower().
The exception received:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at hamming_code.HammingCoder.computeParityBits(HammingCoder.java:34)
at hamming_code.HammingCoder.computeHammingCode(HammingCoder.java:27)
at hamming_code.HammingCoder.main(HammingCoder.java:61)
A larger section of the code:
static int[] computeHammingCode(int[] inWord, int codeLength) {
int[] parityBits = new int[codeLength - inWord.length];
parityBits = computeParityBits(inWord, parityBits);
return parityBits;
}
static int[] computeParityBits(int[] inWord, int[] parityBits) {
for (int i=0, m=2; m < inWord.length; i++) {
m = (int) Math.pow(m, i);
parityBits[i] = processPower(m, inWord);
}
return parityBits;
}
static int processPower(int m, int[] inWord) {
int counter = 0;
for (int i = 0; i < inWord.length; i++){
for (int n = 0; n < m; n++) {
counter = counter + inWord[i];
}
for (int k = 0; k < m; k++) {
i++;
}
}
if (counter % 2 == 0) {
return 0;
} else
return 1;
}
Error message indicates that it fails for i = 5, but your loop is conditioned on the value of m, so something is wrong with your loop.
Printing the value of i and m for each iteration up to i = 5 will show you the error:
for (int i=0, m=2; i <= 5; i++) {
m = (int) Math.pow(m, i);
System.out.println(i + ": " + m);
}
OUTPUT (Ideone)
0: 1
1: 1
2: 1
3: 1
4: 1
5: 1
As you can see, m is always 1.
That is because first iteration calculates:
i=0,m=2: 2⁰ = 1
i=1,m=1: 1¹ = 1
i=2,m=1: 1² = 1
i=3,m=1: 1³ = 1
i=4,m=1: 1⁴ = 1
i=5,m=1: 1⁵ = 1
Debugging your code should have easily shown you this, faster than getting answer here.
I see nothing to prevent i from exceeding codeLength - inWord.length. That would account for the exception.
You get error because on fist iteration you have Math.pow(m, 0); and it equals to 1. Then m always will be 1, because power of 1 always 1. So i is incremented, but m not. But exit loop conditional m < inWord.length.
This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 8 years ago.
I have an array of n elements and these methods:
last() return the last int of the array
first() return the first int of the array
size() return the length of the array
replaceFirst(num) that add the int at the beginning and returns its position
remove(pos) that delete the int at the pos
I have to create a new method that gives me the array at the reverse order.
I need to use those method. Now, I can't understand why my method doesn't work.
so
for (int i = 1; i
The remove will remove the element at the position i, and return the number that it is in that position, and then with replaceFirst will move the number (returned by remove) of the array.
I made a try with a simple array with {2,4,6,8,10,12}
My output is: 12 12 12 8 6 10
so if I have an array with 1,2,3,4,5
for i = 1; I'm gonna have : 2,1,3,4,5
for i=2 >3,2,1,4,5
etc
But it doesn't seem to work.
Well, I'll give you hints. There are multiple ways to reverse an array.
The simplest and the most obvious way would be to loop through the array in the reverse order and assign the values to another array in the right order.
The previous method would require you to use an extra array, and if you do not want to do that, you could have two indices in a for loop, one from the first and next from the last and start swapping the values at those indices.
Your method also works, but since you insert the values into the front of the array, its going to be a bit more complex.
There is also a Collections.reverse method in the Collections class to reverse arrays of objects. You can read about it in this post
Here is an code that was put up on Stackoverflow by #unholysampler. You might want to start there: Java array order reversing
public static void reverse(int[] a)
{
int l = a.length;
for (int j = 0; j < l / 2; j++)
{
int temp = a[j]
a[j] = a[l - j - 1];
a[l - j - 1] = temp;
}
}
int[] reverse(int[] a) {
int len = a.length;
int[] result = new int[len];
for (int i = len; i > 0 ; i--)
result[len-i] = a[i-1];
return result;
}
for(int i = array.length; i >= 0; i--){
System.out.printf("%d\n",array[i]);
}
Try this.
If it is a Java array and not a complex type, the easiest and safest way is to use a library, e.g. Apache commons: ArrayUtils.reverse(array);
In Java for a random Array:
public static void reverse(){
int[] a = new int[4];
a[0] = 3;
a[1] = 2;
a[2] = 5;
a[3] = 1;
LinkedList<Integer> b = new LinkedList<Integer>();
for(int i = a.length-1; i >= 0; i--){
b.add(a[i]);
}
for(int i=0; i<b.size(); i++){
a[i] = b.get(i);
System.out.print(a[i] + ",");
}
}
Hope this helps.
Reversing an array is a relatively simple process. Let's start with thinking how you print an array normally.
int[] numbers = {1,2,3,4,5,6};
for(int x = 0; x < numbers.length; x++)
{
System.out.println(numbers[x]);
}
What does this do? Well it increments x while it is less than numbers.length, so what is actually happening is..
First run : X = 0
System.out.println(numbers[x]);
// Which is equivalent to..
System.out.println(numbers[0]);
// Which resolves to..
System.out.println(1);
Second Run : X = 1
System.out.println(numbers[x]);
// Which is equivalent to..
System.out.println(numbers[1]);
// Which resolves to..
System.out.println(2);
What you need to do is start with numbers.length - 1, and go back down to 0. To do this, you need to restructure your for loop, to match the following pseudocode..
for(x := numbers.length to 0) {
print numbers[x]
}
Now you've worked out how to print, it's time to move onto reversing the array. Using your for loop, you can cycle through each value in the array from start to finish. You'll also be needing a new array.
int[] revNumbers = new int[numbers.length];
for(int x = numbers.length - 1 to 0) {
revNumbers[(numbers.length - 1) - x] = numbers[x];
}
int[] noArray = {1,2,3,4,5,6};
int lenght = noArray.length - 1;
for(int x = lenght ; x >= 0; x--)
{
System.out.println(noArray[x]);
}
}
int[] numbers = {1,2,3,4,5};
int[] ReverseNumbers = new int[numbers.Length];
for(int a=0; a<numbers.Length; a++)
{
ReverseNumbers[a] = numbers.Length - a;
}
for(int a=0; a<ReverseNumbers.Length; a++)
Console.Write(" " + ReverseNumbers[a]);
int[] numbers = { 1, 2, 3, 4, 5, 6 };
reverse(numbers, 1); >2,1,3,4,5
reverse(numbers, 2); >3,2,1,4,5
public int[] reverse(int[] numbers, int value) {
int index = 0;
for (int i = 0; i < numbers.length; i++) {
int j = numbers[i];
if (j == value) {
index = i;
break;
}
}
int i = 0;
int[] result = new int[numbers.length];
int forIndex = index + 1;
for (int x = index + 2; x > 0; x--) {
result[i] = numbers[forIndex--];
++i;
}
for (int x = index + 2; x < numbers.length; x++) {
result[i] = numbers[x];
++i;
}
return result;
}