Why is is giving me ArrayIndexOutOfBoundsException in second For loop? - java

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.

Related

Need help solving ArrayIndexOutOfBounds Exception in Java

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

After counting sort the result array has one more element (0) than the original one

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.

Java reverse array method

I'm trying to create a method that takes in an array and then returns that array in reverse. The code I wrote returns the array in reverse, but, the first two values are now 0. Anyone know what I did wrong?
public static int[] reverse(int[] x)
{
int []d = new int[x.length];
for (int i = 0; i < x.length/2; i++) // for loop, that checks each array slot
{
d[i] = x[i];
x[i] = x[x.length-1-i]; // creates a new array that is in reverse order of the original
x[x.length-1-i] = d[i];
}
return d; // returns the new reversed array
}
You are assigning values from an uninitialized array d to x - that's where the zeroes (default value for an int in Java) are coming from.
IIUC, you're mixing two reversing strategies.
If you're creating a new array, you needn't run over half of the original array, but over all of it:
public static int[] reverse(int[] x) {
int[] d = new int[x.length];
for (int i = 0; i < x.length; i++) {
d[i] = x[x.length - 1 -i];
}
return d;
}
Alternatively, if you want to reverse the array in place, you don't need a temp array, only a single variable (at most - there are also ways to switch two ints without an additional variable, but that's a different question):
public static int[] reverseInPlace(int[] x) {
int tmp;
for (int i = 0; i < x.length / 2; i++) {
tmp = x[i];
x[i] = x[x.length - 1 - i];
x[x.length - 1 - i] = tmp;
}
return x; // for completeness, not really necessary.
}
Here is a short way to do it.
public static int[] reverse(int[] x)
{
int[] d = new int[x.length]; //create new array
for (int i=x.length-1; i >= 0; i--) // revered loop
{
d[(x.length-i-1)]=x[i]; //setting values
}
return d; // returns the new reversed array
}
Its simple mistake; you are coping reversed data in x; and returning d. If you will return x, you will get complete revered data.
d[i] = x[i]; // you are copying first element to some temp value
x[i] = x[x.length-1-i]; // copied last element to first; and respective...
x[x.length-1-i] = d[i]; // copied temp element to first element; and temp elements are nothing but array d
So ultimately you have created revered array inside x and not in d. If you will return x you got your answer. And d which is just half baked; so you get default value of 0 for remainign half array. :)
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9};
System.out.println("The original Array: ");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
System.out.println("The Reverse Array is: ");
for (int i = array.length - 1; i >= 0; i--) {
System.out.print(array[i] + " ");
}

Array in the reverse order [duplicate]

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;
}

How do I shift array elements up one position in java?

I am working on a java assignment where I need to delete an integer element in an array and shift the below elements up on space to keep them in order. The array is currently random integers in descending order. I am not allowed to use array.copy because I will need to collect array usage information as part of the assignment. I have tried a ton of different ways of doing this but cannot seem to get it working.
public static void deletionArray(int anArray[], int positionToDelete) {
for (int j = anArray[positionToDelete] - 1; j < anArray.length; j++) {
System.out.println("j is " + j);
anArray[j] = anArray[j + 1];
}
displayArray(anArray);
}
You're iterating until anArray.length (exclusive), but inside the loop, you're accessing anArray[j + 1], which will thus be equal to anArray[anArray.length] at the last iteration, which will cause an ArrayIndexOutOfBoundsException.
Iterate until anArray.length - 1 (exclusive), and decide what should be stored in the last element of the array instead of its previous value.
You're also starting at anArray[positionToDelete] - 1, instead of starting at positionToDelete.
You have two bugs there.
Since this is an assignment, I won't give a complete answer - just a hint. Your loop definition is wrong. Think about this: what happens on the first and on the last iteration of the loop? Imagine a 5-element array (numbered 0 to 4, as per Java rules), and work out the values of variables over iterations of the loop when you're erasing element number, say, 2.
Use System.arraycopy faster than a loop:
public static void deletionArray( int anArray[], int positionToDelete) {
System.arraycopy(anArray, positionToDelete + 1, anArray,
positionToDelete, anArray.length - positionToDelete - 1);
//anArray[length-1]=0; //you may clear the last element
}
public static int[] deletionArray(int anArray[], int positionToDelete) {
if (anArray.length == 0) {
throw new IlligalArgumentException("Error");
}
int[] ret = new int[anArray.length - 1];
int j = 0;
for (int i = 0; i < anArray.length; ++i) {
if (i != positionToDelete) {
ret[j] = anArray[i];
++j;
}
}
return ret;
}
Why do we reserve a new array?
Because if don't, we would use C\C++-style array: an array and a "used length" of it.
public static int deletionArray(int anArray[], int positionToDelete, int n) {
if (n == 0) {
throw new IlligalArgumentException("Error");
}
for (int i = positionToDelete; i < n - 1; ++i) {
anArray[i] = anArray[i + 1];
}
return n - 1; // the new length
}
How's this ? Please note the comment, I don't think you can delete an element in an array, just replace it with something else, this may be useful : Removing an element from an Array (Java)
Updated with 'JB Nizet' comment :
public class Driver {
public static void main (String args []){
int intArray[] = { 1,3,5,6,7,8};
int updatedArray[] = deletionArray(intArray , 3);
for (int j = 0; j < updatedArray.length; j++) {
System.out.println(updatedArray[j]);
}
}
public static int[] deletionArray(int anArray[], int positionToDelete) {
boolean isTrue = false;
for (int j = positionToDelete; j < anArray.length - 1; j++) {
if(j == positionToDelete || isTrue){
isTrue = true;
anArray[j] = anArray[j + 1];
}
}
anArray[anArray.length-1] = 0; //decide what value this should be or create a new array with just the array elements of length -> anArray.length-2
return anArray;
}
}

Categories

Resources