This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
I have a simple for loop which prints the content of an integer array. It keeps throwing java.lang.ArrayIndexOutOfBoundsException exception. I have been scratching my head for couple of hours not knowing what is that I am doing wrong
public class ReverseArray {
public static void main(String[] args) {
int[] nums = {100,90,80,70,60,50,40,30,20,10};
for(int i = 10; i >= 0; i--){
System.out.print(nums[i] + " ");
}
}
}
The ArrayIndexOutOfBoundsException is thrown because you try to access the 11th element in a 10 element array.
Arrays use zero-based indexing, which means that when you do nums[0] you are trying to access the first element of the Array. So:
int[] nums = {100,90,80,70,60,50,40,30,20,10};
System.out.println(nums[0]);
will print
100
As a result of this, when you do nums[10], you are trying to access the 11th element, which doesn't exist. To fix this, you can start on index 9 instead of 10, like:
for(int i = 9; i >= 0; i--){ // "i" starts with a value of 9, so it works
System.out.print(nums[i] + " ");
}
Arrays in most programming language are indexed from 0 by default, so that means the first element which is 100 has an index of 0, so u access it as nums[0]. So from this u can realize that the last element in ur array has an index of 9 which is nums[9] ==10.
ur getting this error because ur trying to access the element at the 10th index even though ur array has elements only upto 9th index i.e nums[0] = 100, nums[1] = 90 ..... nums [9] = 10.
just change the i to 9 like this and it will work like a charm
public class ReverseArray {
public static void main(String[] args) {
int[] nums = {100,90,80,70,60,50,40,30,20,10};
for(int i = 9; i >= 0; i--){
System.out.print(nums[i] + " ");
}
}
}
Related
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
How to print [ ] in an array (Java)
(7 answers)
Closed last year.
I am struggling to properly output the elements of an array in java. I know I should use a for loop to print out the array, but I am not sure exactly where to start in order to make sure all the values are printed after the function call in main. Any advice would be appreciated. Thank you!
/*
1 creator shares with 3 friends
1 minute = 3 shares/ friend
what does it look like after 10 mins
*/
public int[] shares(int minutes, int people){
int[] array = new int [20];
for(int i = 1; i <= minutes; i++){
people += Math.pow(3, people);
array[i] = people;
}
return array;
}
public static void main(String args[]){
Prc test = new Prc();
System.out.println(test.shares(10, 1));
}
In arrays, you should start with zero.
The for loop could be something like this:
for(int i=0; i<myArray.length; i++){
System.out.println(myArray[i]);
}
I've been attempting to reverse a slice of a list in java.
The equivalent in python (though perhaps not the best way - I don't care about this, just want to get my point across) would be:
myList = [0,1,2,3,4,5,6,7,8,9,10]
reverseSlice = myList[2:6]
reverseSlice.reverse()
myList[2:6] = reverseSlice
When I tried to manually implement this in Java, I tried this:
public static int[] reverse(int[] x,int a1, int a2) {
a1--;
int[] rArr = new int[a2-a1+1];
for (int ind = a1; ind<a2; ind++) {
rArr[a2-ind-1] = x[ind];
}
for (int ind = a1; ind<a2; ind++) {
x[ind] = rArr[ind];
}
return x;
}
However, when I run this:
int[] cows1 = new int[]{0,1,2,3,4,5,6,7,8,9,10};
cows1 = reverse(cows1,2,6);
for (int i : cows1) {
System.out.print(i + " ");
}
I get 0 4 3 2 1 0 6 7 8 9 10 .
I'm really confused how I got this, as in my function, I don't introduce new values, so the "0" shouldn't have appeared.
My Question: Why is my code returning values that are not in the list?
The 0 value which is coming might be because of accessing an uninitialized value from rArr array. For the purpose of reversing, an extra array is not required. You can simply swap the values from the starting index to the end index. I have tested the following code and it gives correct output
public class Solution2 {
public static void main(String args[])
{
int[] cows1 = new int[]{0,1,2,3,4,5,6,7,8,9,10};
cows1 = reverse(cows1,2,6);
// both indices are inclusive
for (int i : cows1) {
System.out.print(i + " ");
}
}
public static int[] reverse(int[] x,int a1, int a2) {
for (int i = 0; i < (a2-a1+1)/2; i++) {
swap(x,a1+i,a2-i);
}
return x;
}
private static void swap(int[] x, int i, int j) {
// System.out.println("values swappeed are "+ x[i] + " " + x[j]);
int temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
and the output comes as
0 1 6 5 4 3 2 7 8 9 10
The problem seems to be the first line of your reverse function: a1--; not preserving the original value for your start index.
The method call
The purpose of the reverse function is to reverse only the portion of the array bound by variable values a1 and a2. On a side note, never use meaningless names like that. Better names for these variables could've been startIndex and endIndex or similar naming (a1 and a2 don't really mean anything).
For values (2, 6), the reverse function should extract the portion of the array starting at index 2 and ending on index 6. I am assuming the end index is not inclusive, so it should only grab values at index 2, 3, 4, and 5. However, the first thing the method does is decrement the start index, so it actually starts at index 1.
From there, the function successfully reverse the values located at these indices [4,3,2,1]. The question is now, what happens to the value at index 5? Let's see what this part of the code does new int[a2-a1+1]. The value of a2 is 6 and the new value of a1 is 1 because it was decremented in the first line. That means that your new array is of size [6-1+1] which is 6. That seems to be incorrect. Only 4 values are required to be reversed and the array is one element too big. The last index of this array is defaulted to integer value of 0.
The swap
First loop:
for (int ind = a1; ind<a2; ind++) { // starts with a1 = 1 and a2 = 6
rArr[a2-ind-1] = x[ind]; // rArr[4] = x[1]: first iteration is off by 1
}
Second loop:
for (int ind = a1; ind<a2; ind++) { // a1 = 1, a2 = 6 (starts at 1 and ends at 5 (rArr doesn't have an index 5)
x[ind] = rArr[ind]; // first iteration: x[1] = rArr[1], last iteration x[5] = rArr[5] -> this last index is accessible because array was too big and was initialized to a primitive `int` default value (0).
}
The solution
Make sure your start and end indices are preserved.
Allocate the temp array (if needed) using the original start and end indices for your calculation.
Inside the reverse() method, your first line should've been:
int[] rArr = new int[a2-a1]; // allocates an array of size 4 (6-2)
From here, if the rest of the method is wrong, you will not see a zero anywhere in the reversed array. At worst, you would've seen an offset problem if your start index was erroneously calculated. And that, I think, would've been easy to spot and fix.
If you are new at programming, and even if you are more of an "expert", you should always work out these problems on paper (or on a board) before you attempt to code and walk through your logic. You will be amazed as to how many logic errors you will catch before you code.
This question already has answers here:
Why does the foreach statement not change the element value?
(6 answers)
Closed 3 years ago.
I am currently working on a program that will roll 5 dice and store a random number for each dice in an array.
My problem is my method is only changing the first element and leaving the rest of the elements as 0's. (Only rolling the first dice so to say)
I initialized an array with 5 values, then run this method which takes an array as a parameter, checks if an element is 0, if it is it assigns a random value between 1 and 6.
I've tried doing an enhanced for loop that looks at each element in the array, and theoretically if it is zero, it assigns a random integer between 1 to 6 to it.
public static void rollDice(int[] dice) {
for (int element: dice) {
int roll = (int)(Math.random()*6) + 1;
if (element == 0) {
dice[element] = roll;
}
}
My results are currently: [Random Number, 0, 0, 0, 0]
My expected results are: [5 random integers]
This form of the Java for loop loops over the values, not the indexes, of the array. All of the values are 0 and you're using them as the index. You are setting the first element 5 times because of this.
Use a traditional for loop.
for (int index = 0; index < dice.length; index++) {
// Your roll here
dice[index] = roll;
}
Here
if (element == 0) {
dice[element] = roll;
}
your code says that if it is the first element, then store the result of the randomization. Since other elements are not the first element, in the case of other elements the condition will be false and consequently the roll will not be stored. Remove this if:
//if (element == 0) {
dice[element] = roll;
//}
public static void rollDice(int[] dice) {
for (int i=0;i<dice.length;i++) {
int roll = (int)(Math.random()*6) + 1;
if (dice[i]== 0) {
dice[i] = roll;
}
}
you were changing index 0 5 times because you put the value of array position 0 as the index to change
In dice[element] :
element is NOT the index of the loop, it's the value of the element in the array.
In your case, element is always 0 because java puts 0s in newly created arrays.
You should use an ordinary for loop in this case:
for (int i = 0; i < dice.length; i++) {
int roll = (int) (Math.random() * 6) + 1;
if (dice[i] == 0) {
dice[i] = roll;
}
}
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
The program should print out values stored in an array of size 5 after the user has input the values.
Here is my code:
import java.util.Scanner;
public class Arrays_Qu1 {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int arr[]= new int [5];
System.out.println("Enter a number");
int i;
for (i=0;i<arr.length;i++) {
arr[i]=sc.nextInt();
}
System.out.println(arr[i]);
}
}
After I enter the 5th value, the program does not terminate but instead throws:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
Because you are printing outside the loop and it is trying to print arr[5] which is out of bound of the array. The print should be in loop if you want to print each element.
int i;
for (i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
System.out.println(arr[i]); // to print each element
}
// value of i is now 5, so arr[i] is invalid
System.out.println(arr[i-1]); // to print last element
System.out.println(Arrays.toString(arr)); // to print whole array
You should access the last element of the array like:
System.out.println(arr[i - 1])
but I believe printing just the last element of an array is not what you want. So you should move line
System.out.println(arr[i])
in a for loop and it should be ok.
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.