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.
Related
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.
I want to remove a single element from an array. This is what I have tried so far:
for (int i = pos + 1; i < currentSize; i++)
values[???] = values[i];
currentSize--;
I'm so confused on what goes inside the [???]
If anyone can help I would really really appreciate it.
Arrays are not very kind in nature, as they can't be resized. As soon as you have learned about objects and generics you will pretty much stop using arrays and transition to Collections. But for now, you'll have to create a new (smaller) array and copy all - but one - value. I will keep it very basic, so you learn the most:
int indexToRemove = 3;
Object[] newArray = new Object[values.length - 1];
for (int i = 0; i < newArray.length; i++) {
if (i < indexToRemove) {
newArray[i] = values[i];
} else {
newArray[i] = values[i + 1];
}
}
I didn't know of which type your values are, so I just took Object. You may want to replace that.
The ??? In this case indicates the index of the array where you wish to get the value from. If you have an array A with elements 5, 10, 15, and 20 then each of the elements can be retrieved with their index. I.e. the index for 5 is 0, for 10 its 1.
An array of size n will have n-1 elements in it due to zero indexing (A[0] is the first element).
I have an array of terms (terms meaning an object with a coefficient and a degree, represented as for example 1.0x^6). The array that I have right now contains 3 terms:
[1.0x^6, 4.0x^5, 10.0x^0].
My goal is to create a bigger array with these terms, but ALSO with terms with a 0 coefficient that are not represented in my array. That probably was not too clear, so here is basically what I want my new array to look like:
[1.0x^6, 4.0x^5, 0.0x^4, 0.0x^3, 0.0x^2, 0.0x^1, 10.0x^0].
Currently, I am iterating through my original array, and if the degree equals the new array.length - 1, I am setting newArray[i] = array[i], if that makes sense. For example, for the first term and i = 0, the degree is 6, and so if 6 = newArray.length - 1 (which is 6), then newArray[i] = array[i].
The problem, however is that array is smaller than newArray, so I am getting an out of bounds error. Any ideas on how to fix this? Sorry for the long post, thanks!
EDIT: Here is my actual code. Sorry if the explanation was unclear.
int max = 0;
Term temp;
for(int i=0; i<array.length; i++) {
max = i;
for(int j=i; j< array.length; j++) {
if(array[j].getDegree() > array[max].getDegree()) {
max = j;
}
}
temp = array[i];
array[i] = array[max];
array[max] = temp;
}
Above, the array is sorted in terms of descending degree. I want to now have the new array contain the old terms, but also 0x^i for all the i that are not used in my set of terms.
Term[] newArray = new Term[this.degree()+1];
for (int c = 0; c < newArray.length; c++) {
if (array[c].getDegree()==newArray.length-1-c) {
newArray[c] = array[c];
}
else {
newArray[c] = new Term(0, newArray.length-1-c);
}
}
There are issues in my code above, and I can see that now because in that for loop, array[c] is not defined for any c > 2. Eclipse is telling my that I have an out of bounds error.
Arrays have a fixed size. If you want to create a bigger array, you need to know the size beforehand and define it accordingly. Also, it seems that you are going through both the arrays using the same iteration variable.
I assume you are doing something like this:
for(i=0;i<newArray.length;i++){
newArray[i] = array[i]; //size of newArray is bigger than array
}
Then you will always get an array index out of bounds exception because "array" is smaller than "newArray" and you go out of bounds when i>=array.length.
You need to fix your code logic.
Suppose I create an int array of size N. Then I fill up the array with sorted numbers until index x, where 0 <= x < N-1. How can I find the index x?
Here's one of the examples of the array: {0,1,2,3,4,0,0,0,0,0}, and here's how I generated the array:
int[] arr = new int[10];
for (int i = 0; i < 5; i++) {
arr[i] = i;
}
Is there any Java syntax for this? I am specifically talking about Array not ArrayList.
====UPDATE====
Sorry for the confusion, the above array was just an example. Suppose the partially initialized array is given, such that we don't know how it was generated. Again, to be clear, the array can also be initialized as {0,0,0,1,2,6,7,0,0,0,0} where the last 0,0,0,0 part is the part from being uninitialized, whereas the first 0,0,0 is deliberately written by somebody else.
You should use Integer class and not int primitive data type. Read about more things you can do with Integer class
Integer arr[] = new Integer[10];
This is initialized to null for each element. Now you can add number to it.
public int indexOfArray(Integer [] arr) {
int i=0;
while(arr[i]!=null) {
i++;
}
return i;
}
You said your array is sorted. So, you can search for the biggest element into the array and then uses Arrays.asList(arr).indexOf(biggestElement);
int biggetsElement = arr[0];
for(int i=1; i < arr.length; i++){
if(arr[i] > biggestElement){
biggestElement = arr[i];
}
}
int index = Arrays.asList(arr).indexOf(biggestElement);
I'm not sure if it will work with int elements, if not you can use Integer elements instead.
Not possible as specified. What if the "sorted values" are all negative and end at -1, e.g.:
[-5,-4,-3,-2,-1, 0,0,0,0]
vs. "sorted values" that are all non-positive but end in 0 (spaces added to emphasize the end of the initial sorted numbers)
[-5,-4,-3,-2,-1,0, 0,0,0]
There's no way to tell afterwards which 0 is the "first" unsorted one.
Assuming you dont know what x is, and assuming that the only value of uninitialized elements is 0, and that all initialized elements cant have the value 0 (which is not true in your case), then you will just have to do a linear search for it -
int i=0;
while(arr[i]!=0) i++;
return i
Create for loop and put in it condition that will check if next element is sorted
Code:
int x
for(int i=0;i<arr.length;i++)
if(arr[i+1]-arr[i]!=1)
x=i;
You can use this :
int index = Arrays.binarySearch(theArray, 0);
Condition : the array must be sorted
edit
Use Integer :
Integer[] theArray = {0, 0, 0, 1, 2, 4, 7, null, null, null};
int index = Arrays.binarySearch(theArray, null);
Say I have an array of 10 elements. Another part of my program determines I must remove the item at index 4.
What is the most efficient method to remove the item and shorten the array?
I wrote the following method, however it does not seem to work properly. Am I missing something, for example if the index to remove is 0? The method is called by sending an array and the index to be removed.
I realize there are Array Lists and other types of lists. However this is an assignment for a programming course and MUST use ARRAYs.
//Removes the index from the array and returns the array.
NumberTile[] removeAndTrim(NumberTile[] array, int index){
NumberTile[] save = array;
array = new NumberTile[save.length-1];
for (int i=0; i<index; i++){
array[i]=save[i];
}//end for loop
for (int j=index; j<save.length-1; j++){
array[j]=save[(j+1)];
}
return array;
}//end removeAndTrim
public NumberTile[] removeAndTrim(NumberTile[] a, int index){
NumberTile[] result = new NumberTile[a.length-1];
for (int i = 0; i < result.length; i++){
result[i] = a[((i < index) ? i : i + 1)];
}
return result;
}
Your most efficient way would be one loop / traversal and one array creation.
(Without using arraycopy that is).
Note: This doesn't alter the values of the parameter array at all, just returns a new one.
Your method is the most efficient possible assuming this is an exercise where you are not allowed to use libraries, utility classes like arraylist or System.arraycopy. Reasoning:
You can't avoid constructing a new array since a) you need one that is one element shorter and b) Java arrays are fixed size so you can't change the existing one
You need to copy length-1 elements in order to populate the new array. Doing this in a tight loop is the fastest you can do in pure Java.
As a style point, you should probably call the new array "result" or somthing similar and avoid the fiddling around with trying to save the array. This is pointless - you can't alter the input parameter.
Note that your function needs to be used as follows:
NumberTile[] newArray=removeAndTrim(oldArray,index);
NumberTile[] removeAndTrim(NumberTile[] array, int removeIndex) {
NumberTile[] newArray = new NumberTile[array.length - 1];
for (int i = 0; i < removeIndex; i++) {
newArray[i] = array[i];
}
for (int i = removeIndex + 1; i < array.length - 1; i++) {
newArray[i] = array[i + 1];
}
return newArray;
}