This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I was learning about for loops and whenever I do this loop
String[] fruits = {"Apple", "Banana", "Orange"};
for (int k = fruits.length;k > 0; k--) {
System.out.println(fruits[k]);
}
and I get this error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at helloworld.HelloWorld.main(HelloWorld.java:439)
Java Result: 1
BUILD SUCCESSFUL (total time: 10 seconds)
and I don't want to do a for each loop.
Thanks in advance
Array indexes for a Java array start at 0. So if there are 3 things in the array, their indexes are 0, 1 and 2.
You've set up your loop so that it starts at k = 3, and on subsequent iterations (if it reached them), it would have k = 2 then k = 1.
But these don't match the indexes in the array. In particular, when k = 3, there's no matching entry in the array, which is what's making your program crash.
You need to change the way your loop is set up, so that it iterates k = 2, then k = 1, then k = 0. May I suggest the following change?
for (int k = fruits.length - 1; k >= 0; k--) {
Everything else can stay the same.
Related
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 been trying to fill my
int[][][] sudoku = new int[5][9][9];
array with
String[][] tmp = new String[21][21];
tmp[][] holds numbers like
005700020009600020
490060010140050030
For example this code works perfect and it gives me the number I want
System.out.println(Integer.valueOf(tmp[4][10]));
But this code
//sudoku1
b=0; c=0;
for (int i = 0; i < 6; i++) {
for (int j = 9; j < 18; j++) {
sudoku[1][b][c] = Integer.valueOf(tmp[i][j]);
c++;
}
b++;
}
throws "Index 9 out of bounds for length 9" error
You have c defined outside both loops, and added 1 each execution in the inner loop. The inner loop gets executed 6*9 times, so c can reach even the value 54, but it throws exception when it reaches 9 when trying to use sudoku[1][b][c], as the array indexes for the third element of the multiarray sudoku go from 0 to 8.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
what I attend to do is when the array(from 0 to n-1) is given, to sum the array values with the index minus multiple of 3 start from the end.
for example, when 7 arrays are given, I want to sum a[0] a[2] a[3] a[5] a[6].
below is error part of the code I programmed.
int j = 0;
for(int i=0; i<n; i++){
j = i*3;
if(i!=n-j)
r += array[i];
}
my code can't read the condition and just sum all the array values.
I don't know why. can someone help me ?
Let's debug!
first time through the loop:
i = 0
j = i * 3 soo... 0
if (0 != 7 - 0) ... - it's not, of course, so i = 0 qualifies and is added.
next loop:
i = 1
j = 3
if (1 != 7 - 3) ... - it's not, of course, so i = 1 qualifies and is added.
Which you did not want.
Given that this is homework, this should be enough for you to take another step and figure out what you SHOULD be doing here. I will give some tips:
You can loop, counting backwards, just as well. You'd have to use i-- of course (decrement i by 1 every time), and you'd use int i = n or perhaps int i = n - 1 as initializing expression in your for loop.
That whole 'is it a 3rd factor from the top' part cannot be calculated using i at all, you'd need something separate for this. You can declare variables outside (you already did that, int j = 0, but you're not looking for 0 so much as 'the first index from the top I do not want'. Then you can use if to check if it is that index. If so, you don't want to add that number to your sum AND you want to update your j.
For tasks like that the modulo operator is usually your friend.
I tried it like this and it works:
int r = 0;
int[] array = new int[7];
for(int i = array.length; i >= 0; i--){
int numberOfIteration = array.length - i;
if(numberOfIteration % 3 > 0){
System.out.println("Add array[" + i + "]");
r += array[i];
}
}
This question already has answers here:
Generating Unique Random Numbers in Java
(21 answers)
Closed 6 years ago.
for (int x = 0 ; x < chosenQ.length ; x++)
{
chosenQ [x] = r.nextInt (9);
c.println (chosenQ [x]);
}
This generates 5 ints between 0 and 9. How do i make it so it will not have duplicate ints when generating it?
Create an array with 10 elements from 0 to 9
Shuffle the array
Take the first five elements
In pseudo code
array = [0, 1, ..., 9]
array.shuffle.take(5)
You'll have to keep a record of which numbers were chosen already.
One way you can do that is by storing the values in a boolean array where all values are initialized to false. When a random value is generated, the element at that index is set to true. Then, for each generated number, you can simply check if the element at that index is true or false.
For example,
// array of booleans initialized to false
boolean[] array = new boolean[chosenQ.length];
for (int x = 0 ; x < chosenQ.length ; x++)
{
int i = r.nextInt(9);
// check if value was chosen already
while (array[i] == true)
i = r.nextInt(9);
// set generated value's index in array to true
array[i] = true;
chosenQ[x] = i;
c.println(chosenQ[x]);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I would like to for-loop a set of numbers and change their positions in each line. It reads a series of integers (at most 10) until a non-integer has been inputted from the keyboard. My expected result is something like this:
>> 4 0 3 4 2 q
4 0 3 4 2
0 3 4 2 4
3 4 2 4 0
4 2 4 0 3
2 4 0 3 4
Can anybody teach me how to deal with it? Thanks in advance.
With some knowledge of modular arithmetic you can fold an array around into a circle. Observe that the starting point of each index shifts to the right by one place from the starting point of the previous row. So you do your loop like this:
n := length of the array
for i = 0 to n-1 (assuming the array is zero-based)
j := i
do loop
print(array[j])
j := j + 1
j := j%n
until j = i
end for
This is a language independent pseudo-code. Adapt it to whatever language your're coding in.
Here is a method to shift the numbers like you want. I took the liberty of commenting it to give you a better understanding of what's going on.
public static void shift(int[] numbers) {
//Store the first element
int first = numbers[0];
//Start for-loop at the beginning of the array, stop before the last element
for (int i = 0; i < numbers.length - 1; i++)
//Take the number at the next index (i + 1) and store it in the current index (i)
numbers[i] = numbers[i + 1];
//Don't forget about the first number!
numbers[numbers.length - 1] = first;
}
The following snippet should change the contents of the array to be {0, 3, 4, 2, 4}
shift(new int[] {4, 0, 3, 4, 2})
Here is a complete, runnable class file.
import java.util.Arrays;
public class Shift {
public static void main(String[] args) {
int[] numbers = new int[] {4, 0, 3, 4, 2};
shift(numbers);
System.out.println(Arrays.toString(numbers));
}
public static void shift(int[] numbers) {
//Store the first element
int first = numbers[0];
//Start for-loop at the beginning of the array, stop before the last element
for (int i = 0; i < numbers.length - 1; i++)
//Take the number at the next index (i + 1) and store it in the current index (i)
numbers[i] = numbers[i + 1];
//Don't forget about the first number!
numbers[numbers.length - 1] = first;
}
}
EDIT:
To use an ArrayList called list, you can use the following snippet:
list.add(list.remove(0));
This is because ArrayList.remove(int) will return the object removed from the array, so we can just add it on to the end.
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
Here's my code:
int myArray[]={1,2,3,4,5,6,7,8};
for(int counter=myArray.length; counter > 0;counter--){
System.out.println(myArray[counter]);
}
I'd like to print out the array in descending order, instead of ascending order (from the last element of the array to the first) but I just get thrown this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
at task1.main(task1.java:14)
Why is this happening? I was hoping that by using myArray.length to set the counter to 8, the code would just print out the 8th element of the array and then keep printing the one before that.
Arrays in Java are indexed from 0 to length - 1, not 1 to length, therefore you should be assign your variable accordingly and use the correct comparison operator.
Your loop should look like this:
for (int counter = myArray.length - 1; counter >= 0; counter--) {
The first index is 0 and the last index is 7 not 8
The size of the array is 8
use myArray.length-1
for(int counter=myArray.length-1; counter >= 0;counter--){
System.out.println(myArray[counter]);
}
The problem here is this piece of code: myArray.length. In Java, as in most other languages, Data structures are 0 based, so the last element has an index of structure.length - 1 (and the first being 0). So in your case, you should change your loop as follows:
for(int counter=myArray.length - 1; counter >= 0;counter--){
System.out.println(myArray[counter]);
}
You're starting at the wrong index. Do it like this:
for(int counter= myArray.length - 1; counter >= 0;counter--) {
The last index of an array is its length minus 1.
the counter is starting at the index of myArray.length which is actually counted from 1 instead of 0..
for(int counter=myArray.length - 1; counter > 0; counter--){
int myArray[]={1,2,3,4,5,6,7,8};
Here, given array length is 8 as the count starts from 1 but coming for the index myArray[0] = 1;
and so on.... here index count starts from 0.
So in your piece of code
for(int counter = myArray.length - 1; counter >= 0; counter--) {
goes out of the array boundary so it shows you ArrayIndexOutOfBoundsException.