Checking length of Arrays before setting values - java

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.

Related

Out of bounds exception in double dimensional array

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];
}

i want fix my method to reverse int array

trying to write a method reverseIntArray(int[] array) which should return a reverse copy of an integer array. For example, if array = [1,2,3,4], then the method should return the array [4,3,2,1].
The program compiles without any error messages. What are the errors causing incorrect incorrect behavior of the program at runtime?
public static int[] reverseIntArray(int[] array) {
int[] result = new int[10];
int j = array.length;
for (int i = 1; i < array.length; i++ ) {
result[i] = array[j];
j++;
}
return result;
}
how should the error be corrected?
what exactly is the error?
what effect the error would have?
You need to set j to be array.length -1 instead of array.length and decrement it instead of incrementing it, and start your for loop index at 0 not 1.
There are a couple of issues with your code:
Your result array is being created with a size of 10 rather than the size of the array being passed in. This will cause an issue if you pass in an array with a smaller or larger size than 10. You can resolve this with: int[] result = new int[array.length];
You're initializing i with a value of 1. Java arrays start at index 0, so your loop will skip populating the first element of the array. You instead want: for (int i = 0; i < array.length; i++) {
Because java arrays start at index 0, the last element's index will be 1 less than array's size. You want: int j = array.length - 1;
You want to retrieve array's elements in reverse order, but your code is incrementing j rather than decrementing it. You want j-- where you have j++
To solve array related problem you must know only about its storage in memory and its index.
In your solution you are trying to overwrite values. In your solution you need to make sure that you are saving older value before writing any new value to any index.
NOTE: You must know that how to swap two numbers.
int[] arr={1,2,3,4};
int i=0;
int j=arr.length-1;
while(i<j)
{
//Swapping two numbers
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
i++;
j--;
}
You can also do the same using for loop.

Java Null Pointer with String Array [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have been coding a basic method to take an array of strings, find the largest length and return a string array containing on values that are equal to the highest length of the array. I keep getting a null pointer exception and i am not sure why. The code is:
String[] allLongestStrings(String[] inputArray) {
int compare = 0;
int k = 0;
String[] use = new String[20];
for (int i = 0; i < inputArray.length; i++) {
if (inputArray[i].length() > compare)
compare = inputArray[i].length();
}
for (int j = 0; j < 20; j++) {
if (inputArray[j].length() - compare == 0) {
use[k] = inputArray[j];
k++;
}
}
return use;
}
for (int j = 0; j < 20; j++) {
if (inputArray[j].length() - compare == 0) {
use[k] = inputArray[j];
k++;
}
}
This will only work if inputArray has at least 20 elements. In the code above, you're doing the correct thing: for (int i = 0; i < inputArray.length; i++). I think you just need to change this second for statement to be the lesser of 20 or the length of inputArray.
inputArray doesn't contain 20 elements. Don't just throw out and hard code a length value for your the array you're going to return. Actually determine what the true length is going to be because you could be too low on that value and if your not then you could end up with a bunch of null elements.
If allowed use an ArrayList or String List object which doesn't require a preset length (size) instead of a 1D String Array which does require length initialization: List<String> list = new ArrayList<>();. You can simply just add to it with the List.add() method.
If you must use a Single Dimensional Array then use another for loop to determine how many string elements actually have the same length as what is held within the compare integer variable. Always iterate through the original array (inputArray). This for loop would be very much like your second for loop except you would increment a integer counter variable upon all elemental lengths that equal the value held within the compare variable.
Eliminate the formula in your if statement condition contained within your second for loop. I think (IMHO): if (inputArray[i].length() == compare) {...} should be sufficient, it's much easier on the eyes. ;)
Just a thought for pizazz....perhaps add the actual Array index to the string that is added to the 1D String array named used. Use a delimiter of some sort to separate the two.

How to check index of integer array element in java? [duplicate]

This question already has answers here:
How to find the index of an element in an array in Java?
(15 answers)
Closed 6 years ago.
In the below code I can get the length and element of array. if I have to check what is the index number at run time for every element, how can I check that?
If I print the value of i from loop every time with the array element it will give the same value, will that be correct to consider the value of i as index value of array?
Another confusion in during the debug in eclipse it shows id value of array is different than the loop value.
public class FirstArray {
public static void main(String[] args) {
int[] arr = {11,12,13,14,15,16,17,18,19,20};
int onelength = arr.length;
System.out.println("Size of Array is: " + onelength);
for(int i = 0; i < arr.length; i++){
System.out.println("element of aray is: "+ arr[i]);
}
}
}
Yes, value of i will be the index value. I would suggest you to go through basics of Java arrays.
The question itself is not clear. The loop bounds are definitely different from the index value of the array. If you want to print the loop bounds along with the value at the index, just print i in the loop.
For your question "what is the index number at run time for every element, how can i check that?" Refer to the solution bellow:
Where is Java's Array indexOf?
For your question "If i print the value of i from loop every time with the array element it will give the same value, will that be correct to consider the value of i as index value of array?"
The array index starts from 0, so if your array length is 10 then index values will be 0 to 9. Thus, if you start your loop from i=0 then the index value will be same as i, but if you start your loop from i=1 then the index value will be i-1.
Will that be correct to consider the value of i as index value of
array?
Of course it'll be correct, i is actually the index of the array.
Another confusion in during the debug in eclipse it shows id value of
array is different than the loop value
Yes, it shows because it's really different, take a look:
for(int i = 0; i < arr.length; i++) {
System.out.println("element of aray is "+ arr[i]); // It prints the element itself -> 11 12 13 14 15.. and so on
System.out.println("iteration number "+ i); // It prints the index of iteration -> 0 1 2 3 4 5.. and so on
}
You may want to clarify what exactly you are searching for.
An array stores a value at a given index (starting at index zero, and going up to index length-of-the-array-minus-one).
The traditional way of creating an array is the following:
// Create an empty array that is able to hold 3 values
int[] numbers = new int[3];
numbers[0] = 11;
numbers[1] = 15;
numbers[2] = 13;
If we now print the values in the index order, we receive 11, 15 and 13. Here's the code:
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
So, we see with numbers[i] = 14 we can assign the value 14 to the index i of the array. And with System.out.println(numbers[i]), we can print the value the array has stored at index i.
An array has a fixed length which needs to be specified at creation, it is not a flexible data structure (but pretty fast and small). Thus, if you are trying to access numbers[100] but we said numbers can only hold 3 values, then you will get an ArrayIndexOutOfBoundsException.
Your provided code is a short-hand for the traditional way:
int[] arr = {11,12,13};
which does the same as
int[] arr = new int[3];
arr[0] = 11;
arr[1] = 12;
arr[2] = 13;
If you want to search for the index, given the value (assuming the values are unique), you need to search the whole array until you find the index. Here's some code:
public int getIndex(final int[] array, final int value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
// Value found
return i;
}
}
// Value not found
return -1;
}
Note that the search code is pretty slow, because you may need to search the whole length of the array (worst case). Other data structures may be more useful depending on your usage.

The most common element in 2d array.How to optimize?

I have this task, find the most commonly seen element in int[][] array and print the number and times repeated.I solved the problem.
A friend of mine said that having 4 for()s is a bad idea.So I decided to try optimising it to remove one or two, but couldn't figure a way.
So here it is:
int cnt, element = arr[0][0], numberRepeats = 0;//cnt-counter,what's the element ,how many times it's repeated
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {//those two for's are for the current element
cnt = 0;//counter is nullified
for (int j2 = i; j2 < arr.length; j2++) {
for (int k = 0; k < arr[j2].length; k++) {//and those two are the compared element
if (arr[i][j] == arr[j2][k]) {//if the current element is the same as the compared element,increase counter
cnt++;
}
}
if (cnt > numberRepeats) {//after the compared element is done comparing and the number of repeats of the current element is more then the lastly checked element
element = arr[i][j];//we get the element ,and how many times it's repeated
numberRepeats = cnt;
}
}
}
}
The only optimisation that I could think of was starting the counting from the current element till the end.
Please give me some more ideas. All the answers I could find were for the 1D array, and they were all pretty much the same code.
You can just iterate your whole array and count the occurrences of every element in a map.
Map<Integer, Integer> elementsCounts = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
Integer count = elementsCounts.get(arr[i][j]])
if(count == null){
count = 0
}
elementsCounts.put(arr[i][j]], count+1)
}
}
Now all it gets is to find the key with the maximum value in the map.
We need to use Map and as well as Set (Set to identify the duplicate elements in a row), only using Map will overlook an edge case scenario where duplicate value in a row may result in incrementing the counter. And finally will be considered as a common value.
Summarizing in below steps:
Populate map with key as a the value of array [i][j] and Map's value as a counter.
IF element is absent in the Map then add key-value pair, Mpa's value as counter initializing from 1.
ELSE, update the element in the Map incrementing the counter with 1
Before incrementing the counter check for duplicate value in the row using Set
Finally, iterate the Map using entrySet() and print only those element whose counter is equal to length of array.
input e.g.:
Integer [][] array = {{1,2,3},{1,4,5,5},{1,5,7}};
output result:
{1}

Categories