reverse for loop for array countdown - java

I get the error..
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at Reverse.main(Reverse.java:20).
There is not wrong in the syntax so im not sure why when it compiles it gets an error?
public class Reverse {
public static void main(String [] args){
int i, j;
System.out.print("Countdown\n");
int[] numIndex = new int[10]; // array with 10 elements.
for (i = 0; i<11 ; i++) {
numIndex[i] = i;// element i = number of iterations (index 0=0, 1=1, ect.)
}
for (j=10; j>=0; j--){ // could have used i, doesn't matter.
System.out.println(numIndex[j]);//indexes should print in reverse order from here but it throws an exception?
}
}
}

You declared array on integers of 10 elements. And you are iterating from i=0 to i=10 and i=10 to i=0 that's 11 elements. Obviously it's an index out of bounds error.
Change your code to this
public class Reverse {
public static void main(String [] args){
int i, j;
System.out.print("Countdown\n");
int[] numIndex = new int[10]; // array with 10 elements.
for (i = 0; i<10 ; i++) { // from 0 to 9
numIndex[i] = i;// element i = number of iterations (index 0=0, 1=1, ect.)
}
for (j=9; j>=0; j--){ // from 9 to 0
System.out.println(numIndex[j]);//indexes should print in reverse order from here but it throws an exception?
}
}
}
Remember indices starts from 0.
.

Java uses 0-based array indexes. When you create an Array of size 10 new int[10] it creates 10 integer 'cells' in the array. The indexes are: 0, 1, 2, ...., 8, 9.
Your loop counts to the index which is 1 less than 11, or 10, and that index does not exist.

The array is of size 10, which means it is indexable from 0 to 9. numIndex[10] is indeed out of bounds. This is a basic off-by-one error.

An Array in java that has 10 elements goes from 0 to 9. So your loops need to cover this range. Currently you are going from 0 to 10, and 10 to 0.

Related

Why this for loop of array uses newARRAY.length-1?

Hello I'm beginner at java now I've arrived to arrays here is a for loop to sort number from highest to lowest, my question is why the instructor used
newARRAY.length-1
?
public static int [] integers;
public static int [] sortArray(int[] array){
boolean PeaceArray = true;
int temp;
int [] newARRAY = Arrays.copyOf(array,array.length);
while(PeaceArray){
PeaceArray = false;
for(int i=0;i<newARRAY.length-1;i++){
if(newARRAY[i]< newARRAY[i+1]){
temp = newARRAY[i];
newARRAY[i] = newARRAY[i+1];
newARRAY[i+1] = temp;
PeaceArray = true;
}
}
}
return newARRAY;
}
Normally the first index of a java array starts from zero (0), but the length property of
the arrays gives an actual count of the array.
For example, consider the following integer array:
int[] numbers = {40, 55, 63, 17, 22, 68, 89, 97, 89}
This array can be represented graphically as well like below
So if we are to run a loop for this array like:
for(int i=0; i<numbers.length; i++){
//this loop runs 9 times
}
I the above loop i was initialized to 0 and the maximum value i can get to is 8 but the loop will run 9 times because if you count all the way from 0 to 8 you get 9
But if you run a loop like this
for(int i=0; i<numbers.length-1; i++){
//this loop runs 8 times
}
The loop will run 8 times but the maximum value i can get to is 7
Your instructor used newARRAY.length-1 because he didn't want the maximum value of i to exceed the immediate lower number following newARRAY.length-1 because he was using the value of i+1 to index the array newArray somewhere in the code.
If he hadn't used newARRAY.length-1 in the code, when i gets to its maximum value, newARRAY[i+1] would give an IndexOutOfbounds error, because the last index of newARRAY would have been exceeded because of the 1 he is adding to i to access the newARRAY
I hope you understood this.
Array start the index with 0
ex:
int a[]={1,2,3,4,5};
then a.length=5 but a[5] does't exits in the array
a[0]=1
a[1]=2
a[2]=3
a[3]=4
a[4]=5
for this reason we use a.length-1 instead of a.length

ArrayList out of bounds while searching for primal number [duplicate]

This question already has an answer here:
What is a StringIndexOutOfBoundsException? How can I fix it?
(1 answer)
Closed 4 years ago.
I don't get how can it be out of bounds if I bound i by the array size. I get Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 116, Size: 116
eratosthenes(ArrayList <Integer> array) checks for primal every element and deletes it if true, then the process is repeated for the next remained element.
package arrays;
import java.util.*;
public class Examples {
public static void main(String[] args) {
ArrayList <Integer> array = getFilledArrayList(2, 1000);
eratosthenes(array);
System.out.println(array.toString());
}
private static void eratosthenes(ArrayList <Integer> array) {
int index = 0;
int primal = array.get(index);
while (index < array.size() - 1) {
for (int i = 0; i < array.size(); i++) {
if (array.get(i) % primal == 0) array.remove(i);
}
index++;
primal = array.get(index);
}
}
private static ArrayList <Integer> getFilledArrayList(int start, int stop) {
ArrayList <Integer> array = new ArrayList();
for (int i = start; i < stop + 1; i++) {
array.add(i);
}
return array;
}
}
Array bounds are 0-indexed, meaning that the first element in an array is found at index 0. Therefore, the last index that is within the bounds of an array is the array size minus 1. Thus, the bounds of an array in Java span from [0, length - 1], or stated another way, [0, length).
The culprit is the following snippet:
for (int i = 0; i < array.size(); i++) {
if (array.get(i) % primal == 0) array.remove(i);
}
index++;
primal = array.get(index);
If array.remove(i) is called within the loop, the number of values in array is reduced. Paired with the increment of index in the index++ line, this may push index beyond the bounds of array causing an IndexOutOfBoundsException.
For example, if array has a length of 1000 and index has a value of 998, calling array.remove(i) causes the length of array to be reduced to 999. The increment of index causes index to have a value of 999, which is equal to the length of array, resulting in an IndexOutOfBoundsException.
array.size() -1, since the array index starts at zero

Exception in thread java.lang.ArrayIndexOutOfBoundsException: 5

I'm a newbie who is trying to complete the below tutorial
// Create a method called countEvens
// Return the number of even ints in the given array.
// Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1.
/*
* SAMPLE OUTPUT:
*
* 3
* 0
* 2
*
*/
Below is my code
public static void main(String[] args) {
int a[] = {2, 1, 2, 3, 4};
countEvens(a); // -> 3
int b[] = {2, 2, 0};
countEvens(b); // -> 3
int c[] = { 1, 3, 5};
countEvens(c); // -> 0
}
public static void countEvens(int[] x){
int i = 1;
int count = 0;
while ( i <= x.length){
if (x[i] % 2 == 0){
count ++;
}
i ++;
}
System.out.println(count);
}
The code can be run, but I get the below error message
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at apollo.exercises.ch05_conditionals.Ex5_CountEvens.countEvens(Ex5_CountEvens.java:23)
at apollo.exercises.ch05_conditionals.Ex5_CountEvens.main(Ex5_CountEvens.java:10)
May I know what I'm doing wrong here?
The line
while ( i <= x.length)
should be
while ( i < x.length)
If the length of xis 5, for example, the indices are 0, 1, 2, 3 and 4. The index goes from 0 up to one less than the length of the array.
However the tidiest way to do this is to use a for each loop rather than a while loop:
public static void countEvens(int[] x) {
int count = 0;
for (int number : x)
if (number % 2 == 0)
count++;
System.out.println(count);
}
'i' should go from 0 to length()-1, because array indices start at 0, and the index of the last element is length()-1.
Therefore, a correct version of your code would be:
public static void countEvens(int[] x){
int i = 0;
int count = 0;
while ( i < x.length){
if (x[i] % 2 == 0){
count ++;
}
i ++;
}
System.out.println(count);
}
For your specific purpose, a for loop would be simpler.
for(int i = 0; i< x.length(); i++){
if(x[i]%2==0){
count++;
}
}
At while ( i <= x.length), you're looping until i is equal to the length of x. The last index of an array is always length - 1, so change the less-than-or-equals (<=) to just less-than (<). Also, initialize i to 0, as Java arrays are zero-based.
Arrays in Java (and most other languages) are indexed starting at 0. However the length of an array is the count of the elements in the array. So for your array a[]
int a[] = {2,1,2,3,4};
The index goes up to 4, whereas the length is 5.
You are getting an index out of bounds error because you are iterating through the array from 1~5 because of the <= (less than equal to) operator, but the indices of the array are 0~4. When you access each element of the array you should use
if (x[i-1] % 2 == 0) //iterates from 0~4 rather than 1~5
otherwise you can set the iterator int i = 0; and use the less than < operator to ensure the iterator moves 0~4

Histogram project: code throws ArrayIndexOutOfBoundsException

This is the code I've isolated:
public static void randomIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = randomInt(-5, 15);
}
scoreHist(a);
}
public static void scoreHist(int[] scores) {
int[] counts = new int[30];
for (int i = 0; i < scores.length; i++) {
int index = scores[i];
counts[index]++;
}
}
But whenever I run this, it gives me this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: (Insert Random # Here)
at arrayhistogram.ArrayHistogram.scoreHist(ArrayHistogram.java:39)
at arrayhistogram.ArrayHistogram.randomIntArray(ArrayHistogram.java:31)
at arrayhistogram.ArrayHistogram.main(ArrayHistogram.java:21)
I'm lost with this. Ideas? I'm really stuck and have been going in circles with this for a while now.
int index = scores[i];
counts[index]++;
according to the randomInt (-5,15), it's possible the index can be negative.
Change
counts[index]
to
counts[index + 5]
This is because index comes from the a array whose elements are initialized to values between -5 and 14 inclusive. However only values between 0 and 29 inclusive are allowed as indices to counts, hence you need to add 5.
So this is the stuff that your code does :
You pick 'n' random numbers from -5 to 15 ( say n=5 ), push them into an array
Say, the array becomes
scores[] = {0,1,1,5,-3}
Now, you are passing this created array in the scoreHist().
Now, see the state of variables during run time
i scores[i] index counts[index]
--- --------- ----- ----------------------
//1st iteration
0 scores[0]=0 0 counts[0]=counts[0]+1 -> 1
Everything goes fine in the first iteration.
//2nd iteration
1 scores[1]=1 1 counts[1]=counts[1]+1 -> 1
Everything goes fine here as well. Now "counts[] = {1,1}"
//3rd iteration
2 scores[2]=1 1 counts[1]=counts[1]+1 -> 2
Things go alright. counts[1] has been updated. Now "counts[] = {1,2}"
//4th iteration
3 scores[3]=5 5 counts[5]=counts[5]+1 -> 1
Things go absolutely fine here .
//5th iteration
4 scores[4]=-3 -3 counts[-3] !!!!!!!! It is out of bound limits for the
array. This index does not exist.
This is what causes the exception that you have
Hope this helps.

Reversing elements of an array

Given an array a and two other int variables, k and temp, write a loop that reverses the elements of the array.
for (k = 0; k < a.length-1; k++) {
temp = a[k];
a[k] = a[a.length-1-k];
a[a.length-1-k] = temp;
}
This is not working. Any idea why?
E.g., for a = [0, 1, 2, 3, 4, 5] you'll switch 0 and 5 twice: when i == 0 and when i == 5. This double-switching will put both elements into their original positions: (0, 5) -> (5, 0) -> (0, 5).
Try to make your loop to go through half of array only: so each pair is switched once.
You need to stop your loop at a.length/2 (in the middle).
for(k=0;k<a.length/2;k++)
This should work for odd and even length arrays if this is integer division.
check this at my blog hope this going to help http://codeheaven.wordpress.com/
Here is the code from above link:
public class ArrayReversing {
public static void main(String a[]){
int arr[]={ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 };
int temp;
int as = arr.length;
int k = as – 1;
System.out.println(“Array Before Reversing”);
printArray(arr);//method used to print array on screen
ArrayReverse://using loops with title
for(int i = 0; i < arr.length/2 ; i++){
temp = arr[k];// swaping
arr[k] = arr[i];
arr[i] = temp;
k–;
}
System.out.println(“Array After Reversing”);
printArray(arr); // calling the method printArray to print the elements of array
}
static void printArray(int ar[]){
PrintArray:
for(int l:ar)
System.out.println(l);
}
}
Output:
Array Before Reversing
1
2
3
4
5
6
7
8
Array After Reversing
8
7
6
5
4
3
2
1
Use a Stack. A stack reverses the elements that are added to it. A stack can be described as First In, Last Out (FILO). "Push" adds the elements to the stack and "Pop" removes them.
public static int[] num1 = {1,2,3,4,5,6};
public static Stack<Integer> stack = new Stack<Integer>();
public static void main(String[] args) {
for(int i = 0; i < num1.length; i++){
stack.push(num1[i]);
}
for(int i = 0; i < num1.length; i++){
System.out.print(stack.pop());
}
}
Output:
654321
You are swapping elements from each end of the array... and iterating to the items you've already swapped... is that enough of a hint?
You might also want to look at the ArrayUtils.reverse method.
Here is an example using that method.
I know you cannot use it in this assignment. But you should be aware of this and use it whenever possible, say in your assignments, projects.
This will work
int a[] = {1,2,3,4,5};
for (int k = 0; k < a.length/2; k++) {
int temp = a[k];
a[k] = a[a.length-(1+k)];
a[a.length-(1+k)] = temp;
}
Try this will simply work:
public class ReverseArray{
public static void main(String[] args){
int[] a ={1,2,3,4,5};
for(int i=a.length-1;i>=0;i--){
System.out.print(a[i]);
}
}
}

Categories

Resources