Control positions in an array.
A common mistake when you're new management arrangements is that we can get confused when referring to the positions of the elements. As in other classes, Java provides components that allow us to control possible errors that can arise when working with arrays. One of the most common mistakes is to refer to elements in the array that are not within this limit. That is, try to select the item in position 11 when the array has a length of 10 elements. If you incur an error like this then it throws an ArrayIndexOutOfBoundsException . This exception indicates that we are referring to a position outside the limit allowed in the settlement.
The following example throws an ArrayIndexOutOfBoundsException.
If you compile and run the above code will present an error message like this:
If we handle this kind of errors then we must make use of try-catch block and catch the exception.
Sort array elements (bubble method) .
One of the most frequent operations in an array is sorted in ascending or descending the elements that compose it. On the Internet we can find a lot of information management methods arrangements, the bubble method is one of the simplest. This method consists in going through the array elements and place them in the correct position according to the order that they should take.
Take the first array element is compared with all others, if there is a greater or lesser number, as the sorting criterion, the element is found stored in a temporary variable, the element comparison is overridden in the element's position more or less, and finally the auxiliary variable element is placed in the position of the item you are comparing. This process is called bubble and repeat now with the remaining elements of the array and you do not take into account the previous positions since it assumes that you are sorted.
The following code shows the elements of an array sorted by an ascending bubble:
0 comments:
Post a Comment