Array index out of bound exception how to overcome [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
public void updateGoalPositions(Goal[][] goals)
{
int row=(goals.length-1);
int col=(goals[0].length-1);
for(int i=0;i<row;i++)
for(int j=0;j<col;j++)
{
if(goals[i][j+1].isHit())
{
Goal temp=goals[i][j+1];
goals[i][j+1]=goals[i][j];
goals[i][j]=temp;
}
else
if(goals[i][j-1].isHit())
{
Goal temp=goals[i][j-1];
goals[i][j-1]=goals[i][j];
goals[i][j]=temp;
}
}
}
goals[i][j-1] shows error. How to override it?

when j = 0, j - 1 gives -1 which causes the error so test condition only if j - 1 >= 0
else
if(j - 1 >= 0 && goals[i][j-1].isHit())
{
Goal temp=goals[i][j-1];
goals[i][j-1]=goals[i][j];
goals[i][j]=temp;
}

On first j-iteration, j=0 and j-1's value is -1
Add if (j-1>-1) for example

When i = 0 and j = 0, goals[i][j-1] is going to mean goals[0][-1] that is your issue, you need to fix your algorithm.

Everywhere you have j+1 you'll exceed the limit in the last iteration.
Why? Because arrays are zero-based in Java, meaning that if you have an array of size N, the indexes will run between [0, N-1]. In your last iteration, when j is N-1, j+1 is actually N, which is out of bounds.
Read about arrays in the JLS - Chapter 10. Arrays.
Note also that you have places where j-1 will be -1 (in the first iteration where j is 0).

Related

Why does this piece of code say variable j might not have been initialized?? It is getting initialized inside the loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
class Searching{
static int search(int arr[], int N, int X)
{
int j;
for(int i = 0; i<N; i++){
if(arr[i] == X){
j = i;
break;
}
}
return j;
}
}
I have initialized j inside the loop. So why does the compiler say j is not initialized when it reaches the return statement. I am not able to understand as I am new to coding.. Please help me
In Java, for loops are pre-test loops: the test (i<N) is executed before the loop body. So if N is less than or equal to the initial value of i (0), then the loop wil never execute and j will never be initialised.
But there’s another issue that the commentators missed: even if the loop executes, if the element being searched for does not exist in the array, j will never be initialised.
On another note, instead of passing N as a parameter, you should be able to get it directly from the array (though I can’t remember how to do it right now).
This is happens because the parameter N can be equals to 0, so the loop isn't must running, or array isn't contains x, so the variable j will not initialize.
I suggest you to initialize like int j = -1;, and than if the method returns -1 you will know that something go wrong (N = 0 or array isn't contains x).

Inverting values in an array [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
The program is meant to invert the values in the array. When the program is run, the only values that show are 3 and 2, then it ends. I've been looking online but I can't figure out why this happens. Switching val[i] for temp in the SOP gives values of 0 and 1 then ends.
int[] val = {0, 1, 2, 3};
int temp;
for(int i=0;i<val.length/2;i++)
{
temp=val[i];
val[i]=val[val.length - 1 - i];
val[val.length - 1 - i]=temp;
System.out.println(val[i]);
}
Because your for loop only iterate for values 0 and 1, then at the end it prints only 0th and 1st elements, try following
int[] val = {0, 1, 2, 3};
int temp;
for(int i=0;i<val.length/2;i++) {
temp=val[i];
val[i]=val[val.length - 1 - i];
val[val.length - 1 - i]=temp;
}
for(int i=0;i<val.length;i++){
System.out.println(val[i]);
}
It makes sense to use val.lenth/2 to only traverse half of the array, swapping values as you go. It does not make sense to only traverse half of the array while trying to print the entire array. Try using another for loop to print out the contents of the ENTIRE array.
edit: I tried not to just give the answer
for(int i=0;i<val.length/2;i++)
val.length/2= 4/2 = 2 so that the for loop will only run twice. Thats why it prints only the 3 and 2.
int[] val = {0, 1, 2, 3};
int temp;
for(int i=0;i<val.length;i++)
{
if(i<val.length/2){
temp=val[i];
val[i]=val[val.length- 1 - i];
val[val.length- 1 - i]=temp;
}
System.out.println(val[i]);
}

Do while loop nested in for loop wont iterate [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I need to enter N which is a number of numbers for which I need to see if they can be divided by 3. Afterwards I need to display what % of numbers from the N I can divide. Numbers need to go from 15 to 62 and they need to loop until I enter the right value each time, but they don't. Instead, they just repeat the for loop regardless of my input. Here is the code:
System.out.println("Enter N number of numbers");
int N = TextIO.getlnInt();
int number;
int counterOfDivisible = 0;
for(int i = 0; i < N ; i++) {
do {
System.out.println("Please enter a number from the 15-62 span");
number = TextIO.getlnInt();
} while (number<15 && number>62);
if(number%3==0)
counterOfDivisible++;
}
System.out.println("% of numbers from the N that can be divided by 3 is " + (counterOfDivisible*100.0)/N + "%");
number can never be <15 and >62 at the same time. Think about your condition.
Thank you all for the quick reply, first time here. Quite silly mistake on my behalf.
This seems to do the trick i was aiming for.
do {
System.out.println("Please enter a number from the 15-62 span");
number = TextIO.getlnInt();
} while (number < 15 || number > 62);

Is this a correct BubbleSort Algorithm? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I wrote the following code to sort the elements in the array values using a BubbleSort. Is this correct or is there anything missing? My test cases are good, but maybe it's the test cases that are also missing something.
public void sort(ValuePair[] values) {
ValuePair value = null;
for (int i = 0; i < values.length; i++) {
for (int j = 1 + i; j < values.length; j++) {
if (values[i].getValue() > values[j].getValue()) {
value = values[j];
values[j] = values[i];
values[i] = value;
}
}
}
}
Your code is correct in that it will sort the array. However it will always require N*(N-1) passes over the array. This is not
the typical algorithm used to implement
a bubble sort. The typical algorithm uses repeat loop with a test for sorted. This is somewhat more efficient because it
terminates as soon as the array is sorted (consider the case where you start with a sorted array).
Read the Wikepedia article on bubble sort it demonstrates this very well.
A somewhat improved version pseudocode version of Bubble Sort goes something like this:
procedure bubbleSort( A : list of sortable items )
n = length(A)
repeat
swapped = false
for i = 1 to n-1 inclusive do
if A[i-1] > A[i] then
swap(A[i-1], A[i])
swapped = true
end if
end for
n = n - 1
until not swapped
end procedure
The lesson here is that while your algorithm and the Wikepedia algorithm both have the same big O characteristics, a small change
in the way they have been implemented can make a significant difference in their actual performance characteristics.

Store repeating sequence of integer in another array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have two arrays a[] and b[].
int a[]={3,1,1,1,7,4,6,6,3,1};
int b[]=new int[a.length];
Array length in actual problem can change.
The values in the array must be less then value of array length as seen.
The output must be:
b = 3 1 0 0 7 4 6 0 3 1
So basically if there is a sequence of same value in a[] then only 1st of its value must be placed at same index in b[] rest should be zero till the sequence exists.
Answer in java syntax will be helpful.
Thank you in advance
int a[]={3,1,1,1,7,4,6,6,3,1};
int b[]=new int[a.length];
int temp = a[0];
b[0] = temp;
for(int i = 1; i < a.length; i++) {
if(a[i] == temp)
b[i] = 0;
else
b[i] = a[i];
temp = a[i];
}
hint:
1) create hashmap to store processed values
2) iterate over the first array: if current value is stored in map, then fill 0, otherwise store this value in HashMap and copy the value to new array

Categories