Out of bounds exception in double dimensional array - java

Trying to find the sum of all even numbers and product of all odd numbers in a double dimensional array.
Why am I getting the following out of bounds exception error ?
Exception java. lang. Array Index Out Of Bounds Exception
While running the code this exception comes for line if(m[i][j]%2==0)

The exact cause of your error is that your 2D array is actually a jagged array, meaning that not every row contains the same number of elements. In fact, the second row only contains three elements, so when you when the following if check:
if (m[i][j]%2 == 0)
you get an out of bounds exception for i=1 and j=3.
You should either make the 2D array non-jagged, or instead use this for loop:
for (int i=0; i < 4; ++i) {
for (int j=0; j < m[i].length; ++j) {
if (m[i][j]%2 == 0) {
s += m[i][j];
}
else {
r *= m[i][j];
}
}
}
}

Your m array's element at index 1 is missing a fourth element:
{30,11,71}

Do not use as limits fixed values (such as 4), but instead use the length provided by the array(s).
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++) {
//...
}
}
Why?
Not all inner arrays have 4 elements (i.e.: {30, 11, 71}), so at the last iteration of the inner loop (j = 3), this code m[i][j] tries to access a value out of the bounds of the array because in some cases there is no position 3, just 0 (1st element), 1(2nd element) and 2(3rd element). Thus you get the mentioned exception.
Side note:
Another problem (mentioned by you) is that you will get r = 0 always because it is initialized to 0 and every time you multiply its value by another one, the result will be 0.
So, in order to fix this you need to add a check in the else condition, like this:
else {
r = r == 0 ? m[i][j] : r * m[i][j];
}

Related

Returning the number of times a number appears in an Array?

So I'm doing a bunch of exercises, one of them asks me to write a method that is passed an array with each slot type int. This method should return the number of times 99 occurs in the array. Here's what I came up with on the fly:
public static int countNum(int[]x)
{
int count = 0;
for (int i = 0; i <= x.length;i++);
{
if (x[i] == 99)
count++;
}
return count;
}
All in all, I just need to write the method. Am I on the right track?
Well, there are two mistakes.
First: i < x.length; it should be like that or i <= x.length - 1; like that or you will get out of your array.
Second:
for (int i = 0; i <= x.length;i++)**;**
{
if (x[i] == 99)
count++;
}
You don't need ; or the next code will be out of for.
array.length returns length of an array and you don't want to iterate from 0 to length, but from 0 to length - 1.
Why? For example if an array is [1, 5] then:
array.length == 2, array[0] == 1, array[1] == 5 but array[2] throws java.lang.ArrayIndexOutOfBoundsException (because it tries to reach an element which is not in the array)
Remove the semicolon after the for statement:
for (int i = 0; i <= x.length;i++);
(a for loop executes statements which comes directly after it, and ";" ends a statement. The for(...) followed by ";" means that you have a loop which does nothing x.length times)

Checking length of Arrays before setting values

I have to set values in a list of string arrays. How do I write the code to avoid an array out of bound exception.
e.g. this is my code:
for (int i = 0; i < childs.getLength(); i++)
{
String[] slotValues = _newValues.get(i);
if (allSlots) {
NodeList slots = childs.item(i).getChildNodes();
for (int j = 0; j < slotValues.length; j++) {
XmlUtil.setTextContent(slots.item(j), slotValues[j]);
}
} else {
for (int j = 0; j < slotValues.length; j++) {
XmlUtil.setTextContent(XmlUtil.getFeature(_slotNames[j], childs.item(i)), slotValues[j]);
}
}
}
I am a beginner and I do not know how to check if the length of values that I am trying to set in the structure does not give array out of bound exception. i.e. it should be equal to the length of array.
I am a beginner and I do not know how to check if the length of values
that I am trying to set in the structure does not give array out of
bound exception. i.e. it should be equal to the length of array.
Since collections in Java are 0 based, having array arr the first element is arr[0] and the last element will be arr[arr.length-1]. Knowing this you can ensure that your iteration variable (array index) is always >=0 and <array.length.
Having index >= arr.length will result in IndexOutOfBoundsException
Bare in mind, that in your code, you are using single iteration variable to index multiple arrays like here
XmlUtil.getFeature(_slotNames[j], childs.item(i)), slotValues[j])
You are using _slotNames and slotValues with the same index, but you are limiting index with j < slotValues.length so it is dependent on slotValues length. If both arrays are of equal length, that is fine. But if they are not, then you will get mentioned exception if _slotNames will have less elements then slotValues.

Removing an element from ArrayList

I have an ArrayList which contain 10 elements and a variable int = 12. Now I want to count how many elements are in array and if are less than 12 to start to count again from 0 and stop to index 2 and remove it, until I will have one element in my array. I tried the following:
int j = 12;
int l = 0;
// Here I check if j is less than array.size
while (j < array.size()) {
for (int i = 0; i < array.size(); i++) {
if (j == i + 1) {
array.remove(i);
}
}
}
// Here is for j greater than array.size
while (array.size() != 1) {
for (int i = 0; i < array.size(); i++) {
l = j - array.size();
if (l < array.size()) {
array.remove(l);
}
}
}
System.out.println(array);
UPDATE:
MyArray = {1,2,3,4,5,6,7,8,9,10};
int=12;
MyArray contain just 10 elements, but I want to delete the index with number 12, as long as index 12 does not exist I should start to count again from zero, and the number 12 is at index 2, That's why I should delete the index with number 2. The second iteration MyArray will contain just 9 elements, and again 12-9=3, I should delete the index with number 3, until I will have just one element in MyArray
Instead of looping twice through the array to remove the last n elements until the length of the list equals j, you could simply use:
while (j < array.size()) {
array.remove(j - 1);
}
If you always want to remove index 2, you could do:
while (array.size() >= 3) { // otherwise you will get a ArrayIndexOutOfBoundsException
array.remove(2);
}
However, you will have two elements left in your ArrayList instead of 1 (at index 0 and 1). You cannot delete ìndex 2 at that point, because it is not a valid index any longer.
Thus, you could either remove index 0/1 afterwards or what I think you want to achieve:
while (array.size() >= 2) { // otherwise you will get a ArrayIndexOutOfBoundsException
array.remove(1);
}
Then only one element will remain in your list at index 0.
Edit: for the update of your question it is
int originalSize = array.size();
while (array.size() >= originalSize - j) { // otherwise you will get a ArrayIndexOutOfBoundsException
array.remove(originalSize - j);
}
However, you will always be left with size - j items in your list. You cannot remove index 3, for example, until you have only one element in your list.
An answer to the updated question:
When you have a list of length 10 and you want to delete the "12th element" you can use the modulo operator:
ArrayList<...> someList = ...;
int toDelete = 12;
int deleteInRange = toDelete % someList.size();
someList.remove(deleteInRange);
The modulo operator will deliver the rest of the integerdivision 12 / 10 (toDelete % someList.size())
You can use this code snippet in a loop in order to remove multiple elements.
If you always want to remove index 2, you could do:
l = j - array.size();
Change this line as below:
int sum = 0;
sum = l - array.size();
if (sum > 0) {
array.remove(sum);
} else {
sum = array.size() - l;
array.remove(sum);
}

java code keeps throwing exception

My code always throws an exception java.lang.String.charAt at this line in my code :
while(0 == charToInt(value.charAt(startValueAt))){
in the code segment,
private static ArrayList<Integer> stringToArray(String value){
ArrayList<Integer> holder = new ArrayList<Integer>();
int startValueAt = 0;
if(value.charAt(0)=='-'|| value.charAt(0)=='+')
startValueAt= 1;
else
startValueAt = 0;
while(0 == charToInt(value.charAt(startValueAt))){
startValueAt++;
}
int startOfValue = value.length() - (startValueAt - 1);
//to make sure that arraylist is right size and last element ends up at zero as well as find starting index of j with above step
//we use value of startValueAt
for(int i = startOfValue, j = startValueAt; j <= value.length() - 1; i--, j++){
holder.add(0, charToInt(value.charAt(j)));
}
return holder;
}
Here is the stack trace:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:686)
at BigInt.stringToArray(BigInt.java:145)
at BigInt.<init>(BigInt.java:35)
at BigInt.multiplyBySingleDigit(BigInt.java:853)
at BigInt.multiplyPositives(BigInt.java:878)
at BigInt.multiplyOneNegative(BigInt.java:920)
at BigInt.multiply(BigInt.java:778)
at BigInt_Add_Sub_Mul_Div_Mod_Demo.main(BigInt_Add_Sub_Mul_Div_Mod_Demo.java:164)
while(startValueAt < value.length() && 0 == charToInt(value.charAt(startValueAt))){
startValueAt++;
}
You are ignoring the case where the String is all 0s. Then you will call value.charAt(value.length()) which throws the exception.
Using the string "+321", by the last for loop the variable 'j' is set to startValueAt and is supposedly pointing to the last integer, i.e. '1'. In other words the 4th character in '+321'. But then you increment 'j' (with j++) and try to find it in the array. This will give you an out of bounds exception.
while(0 == charToInt(value.charAt(startValueAt))){
startValueAt++;
if (startValueAt>=value.length()) break; /*add this line */
}
(1) You need to make sure that value contains at least one number that is not 0 (otherwise, your while-loop will continue until it wants to get a char from value that is out of bounds / doesn't exist)
An attempt to fix this problem might be changing your while-loop to this:
while(startValueAt < value.length() && 0 == charToInt(value.charAt(startValueAt))){
startValueAt++;
}
(2) In your for-loop:
for(int i = startOfValue, j = startValueAt; j <= value.length() - 1; i--, j++){
holder.add(0, charToInt(value.charAt(j)));
}
the variable j is incremented until it equals value.length(). The problem is, if your string has 4 characters you can access the last character using string.charAt(3).
The problem should be fixed by simply changing j <= value.length() to j < value.length().
Remember, arrays and lists always start at index 0.

Arrays and enhanced for loops?

Can someone please explain what is going on in this method?
class test{
public static void main(String args[])
{
int[] x = new int[4];
int[] xy = new int[4];
//System.out.println(xy[0]);
for(int j : x) {
xy[j] += 1;
}
System.out.println(xy[0]); }}
So I thought that the enhanced for loop would be doing this
/**for(int j=0; j < x.length(); j++)
xy[j=0] = 1
xy[j=1]=1
xy[j=2]=1
xy[j=3]=1*/
but from what I've been reading, the enhanced for loop is doing for(int element:array). Still, I don't understand what the for loop in my method is actually doing. I have tried System.out.println() statements to check what was being put into the array xy, but it is either addresses or 0.
Thanks for all the help and apologizes if this is confusing.
For Each loop that you have used in here does assign j a value that is already assigned to array x (which in your case is 0 ).
As according to your case of x and xy array:-
x[0]=0; xy[0]=0
x[1]=0; xy[0]=0
x[2]=0; xy[0]=0
x[3]=0; xy[0]=0
Describing for each loop according to your program case:-
for(j : x)
This implies it will run for 4 times which is the length of your array x.
when running first time the following process will happen
j=x[0] (so j=0 coz x[0] according to your case)
xy[0]=xy[0]+1 (so now xy[0] value becomes 1)
Similarly
for the second run of for each
j=x[1] (so j=0 coz x[0] according to your case)
xy[0]=xy[0]+1 (so now xy[0] value becomes 2 as in previous for each run xy[0]=1)
So all in all finally you will have xy[0]=4 at the end of 4th run of for each loop.
Finally the print statement will print 4.
int[] x = new int[4];
This creates an array of 4 elements. Each element's value is 0.
for(int j : x) {
xy[j] += 1;
}
This iterates through all the values of x. At each iteration, j is the next element in x, but since all elements are initialized to 0, j is always 0. So, the 4 iterations increment xy[0].
Here in the advanced for loop, the int j does not represent the index. Rather it represents the values in the xy[] array. It is not possible to get the index of advanced for loop. If you want index, then you might have to use ordinary for loop.
Ex. If you have
xy[]={5,8,3,4};
for(int j:xy)
{
println(j);
}
then the output would be
5
8
3
4
It should be straight-forward to find out, if you trace through using debugger.
In brief, it is getting each value in x, and use the value as index to increment corresponding value in xy.
It will be more obvious if you initialize both array with meaningful values:
int[] x = {1,1,3,3}
int[] xy = new int[4]; // initialized to 0 by default
after your piece of code, you will find xy containing {0,2,0,2}.
You should understand how enhanced-for-loop is expanded for array:
for (T v : arr) {
// do something
}
is transformed to
for (int i = 0; i < arr.length; ++i) {
T v = arr[i];
// do something
}
Obviously your understanding on how enhanced for loop being expanded is wrong.
In your case you need only for-loop and not enhanced for-loop:
for(int j = 0 ; x.length > j; j ++) {
xy[j] += 1;
}
Problem with your code is that your loop traverse only at index 0 of xy hence you get xy as [4, 0, 0, 0]
int[] x = new int[4];//default values [0, 0, 0, 0]
int[] xy = new int[4]; //default values [0, 0, 0, 0]
for(int j : x) { // j is always 0
xy[j] += 1;// xy[0] += 1
}
You can use the for-loop instead:
for(int i = 0 ; x.length > i; i ++) {
xy[i] += 1;
}
If you want to still use for each then here is the example
a[]={1,2,3,4};
for(int i:a)
{
println(i);
}
Hope it helps!

Categories