Duplicate for-loop practice, beginner needs advice to study - java

Understanding the -1 in the for loop, need detailed explanation with for and if lines of code included?
int[] array = { 2, 5, 1, 2, 3, 5 };
Arrays.sort(array);
// why does this start counting from 1, and if l put 0 it goes to error, out of bounds?
for (int i = 1; i < array.length; i++) {
if (array[i] == array[i - 1]) { // - 1?
System.out.print(array[i]);
}
}

There is nothing inherently wrong with it.
It just makes the iteration to start with i=1 up to the array's length, but since indexing in arrays are zero-based you have to offset it when getting the value.
That is why is array[i-1]
If you put i=0 then you also have to change the ending condition to array.length-1, and you have to access the values by array[i] in order to avoid going out of bounds.

For questions like this, take the code one line at a time and try to follow what it is doing.
The first thing you do here is to create an array, then sort it. After the Arrays.sort(array) call, your array will contain the following:
index 0 1 2 3 4 5
----------------------
contents 1 2 2 3 5 5
Remember, arrays are zero-indexed - that means the very first element is located at index 0. (The contents of the array don't matter, it's the index you want to pay attention to.)
Arrays cannot have indexes less then zero, and they also cannot have indexes greater than their length-1. So, for your example, that means you cannot use -1 as an index because it is less than 0. You also cannot use 6 as an index, since 6 is greater than the length of the array (6) minus one.
In the initialization of the for-loop, you set i equal to 1 for the first iteration. Though unconventional, it's perfectly legal. This simply represents which index we will start from in the array. So for the first iteration of the loop, array[i] will be pointing to the value 2, and array[i-1] points to the value 1.
index 0 1 2 3 4 5
----------------------
contents 1 2 2 3 5 5
i ^
i-1 ^
Now, what if you set i to start at index 0 instead? Well, then array[i] will point to the 0th index (value 1)... but what does array[i-1] point to?
index 0 1 2 3 4 5
----------------------
contents 1 2 2 3 5 5
i ^
i-1 ^
It's pointing to index -1. Since arrays can't have indexes of -1, this is causing your IndexOutOfBoundsException. Hopefully that makes sense.

Related

How to take find the value attached to a specific index of an array

I have to return the value for a specific index of an array.
I am to take the last digit in my array and use that digit as the index for where to look in my array. Meaning if my array is 6543743 I need to return the value at the 3rd index, which should be 4. I have this so far, but it keeps returning 3 - it's taking the final index instead of going to that index for the value.
x = array[array.length-1];
I'm clearly missing something, but I can't figure it out. Thank you!
You need to subset the array twice:
int[] array = { 6 5 4 3 7 4 3 };
int num = array[array[array.length - 1]];
The last value in the array is given by array[array.length - 1], and then this value is used as an index again into the same array.

Java code length -1 meaning [duplicate]

This question already has answers here:
Does a primitive array length reflect the allocated size or the number of assigned elements?
(17 answers)
What does arrays.length -1 mean in Java?
(1 answer)
How do you determine the legal index range for an array?
(1 answer)
Closed 5 years ago.
The community reviewed whether to reopen this question last month and left it closed:
Original close reason(s) were not resolved
class Zillion {
private int zilly[];
public Zillion(int size){
zilly = new int[size];
}
public void increment(){
int i=zilly.length -1;
while(i>=0){
if(zilly[i]!=9){
zilly[i]+=1;
i=-1;
}
else{
zilly[i]=0;
i--;
}
}
}
I just got a basic java code like this and do not know what length -1 means at this part (int i=zilly.length -1;).
Can someone please explain this ?
The size of array is the number of elements in this array, but The first index of arrays is 0. For example :
int zilly[] = {1, 2, 3, 4}
In this example :
zilly.size return : 4
But zilly[4] not exist because the index of the first element is 0
zilly.[zilly.size - 1] return the last element (4).
Hope it helps.
nameOfTable.lenght return the number of element
the first index of Arrays start with 0 ==> (1st - 1 = 0) ,
so the last index is n - 1
int i=zilly.length -1; is the last index of the array, because arrays start at index 0.
A side note, the formatting of this code be improved to better portray what it's doing, for example the line that confused you could be.
int i = zilly.length - 1; simply spacing out the statement correctly makes it a bit easier to understand.
zilly.length -1 defines itself. Total array length (size) -1.
Since the first index of array starts with 0 so the last item is at position n-1 where n is the size of array.
In Java indexing of arrays starts from 0. Therefore the last element of arrays is accessed by zilly[zilly.length - 1]. If you try to access it this way:
zilly[zilly.length]
you will get an out of bounds exception.
The while loop in your code starts from the last index and iterates down the very first element.
zilly.length gives the length of the array, i.e. the number of elements in it.
zilly.length-1 gives the last index of the array because the count of the array begins from 0.
So basically you are iterating in a descending order, i.e. from the last element of the array to the first element of the array.
It means that we want to get the last index in the array.
And then we loop over the array from end to start.
zilly.length it's the array size - but the array's index starts from 0 so the last index is zilly.length-1

Why ArrayList giving unordered output?

I have written java program, to add integer in ArrayList and remove that integer from ArrayList . but it not giving me proper result. here is my code..
public static void main(String args[])
{
ArrayList<Integer> a=new ArrayList<Integer>();
a.add(6);
a.add(7);
a.add(8);
a.add(9);
for(int i=0;i<=a.size();i++)
{
System.out.println("Removed Elements=>"+a.remove(i));
}
}
it giving me output as follows
Removed Elements=>6
Removed Elements=>8
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.remove(ArrayList.java:387)
at CollectionTemp.main(CollectionTemp.java:19)
why i am getting output like this?
Your array:
a[0]=6
a[1]=7 <-- i
a[2]=8
a[3]=9
Then you remove at 1, and i increments to 2:
a[0]=6
a[1]=8
a[2]=9 <-- i
Remember that array indexes start at 0, so the last element is at a.length - 1
You get your exception because the loop condition i <= a.size(), so at the final iteration:
a[0] = 7
a[1] = 9
2 <-- i
When you remove items from a list, or any collection, you either use the iterator, or you use a reverse loop like this.
for (int i = (a.size() - 1); i >= 0; i--) {
System.out.println("Removed Elements=>" + a.remove(i));
}
By going backwards, you avoid the incrementing by 2 problem that has been documented in the other answers.
for first iteration, a.remove(i) causes the element 7 to be removed which is returned by remove method.
For second iteration, the size of list is 3 and you are removing the element at index 2 which is 9. SO remove method returns 9.
In short
Iteration | Size of list | index being removed | element removed
----------+--------------+---------------------+----------------
1 | 4 | 1 | 7
2 | 3 | 2 | 9
If you want a forward loop to remove all elements you could use the following code:
while(!a.isEmpty())
{
System.out.println("Removed Elements=>" + a.remove(0));
}
Your problem is that, as you remove elements, you resize the ArrayList. However, your loop counter is not updated, so you iterate past the bounds of the ArrayList.
ArrayList.remove(index) removes the element from the array, not just the contents of the ArrayList, but it actually resizes your ArrayList as you remove items.
First you remove the 1st element of the ArrayList.
Removed Elements=>6
Here the list has been resized from size 4 to size three. Now the element at index 0 is 7.
Next, you step to the element at index 1. This is the number 8.
Removed Elements=>8
Here the ArrayList has been resized to length 2. So there are only elements at index 0 and 1.
Next you step to index 2.
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 2
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.remove(ArrayList.java:387)
at CollectionTemp.main(CollectionTemp.java:19)
There is no index 2, so you get an IndexOutOfBoundsException.
the index starts with 0 and ends with size - 1
your loop goes from 1 to size - 2
ArrayList indexes start at zero, but your loop starts removing at 1. After adding the elements your arraylist looks like this:
0 - 6
1 - 7
2 - 8
3 - 9
Because your loop starts counting at 1, you will first remove the element labeled 1, which is 7.
The list will then look like this:
0 - 6
1 - 8
2 - 9
Then the loop will remove the element labeled 2, which is now 9.
So the two mistakes are starting at 1 instead of 0, and incrementing the counter after something has been removed (all elements after the removed element will shift down).
In the first iteration , i starts from 1, so your second element is removed ie. 7. Now list has
6
8
9
Next iteration is 2, so third element 9 is removed.
Your output is correct : Here is the explaination.
When the loop is executed for the first time, value of i will be 1. and it execute the statement a.remove(1). after removing the value 7 which is at place a[1], '8will be ata[1]'s place. After that i is incremented and becomes 2 and it removes the element a[2] which is 9.
This is simple logic:
First Iteration i=1:
a[0]=6,
a[1]=7,
a[2]=8;
a[3]=9;
Remove a[i] i.e a[1] removes 7
Second Iteration i=2:
a[0]=6
a[1]=7
a[2]=9
Remove a[i] removes 9
The value of i in the loop goes through the following values
0
1
2
3
4
The array has index with values 0 , 1 , 2 , 3
The loop will run for values 0,1,2,3,4
The array is not displayed ordered bcoz when one value is removed the next value is available at index 0
At i=2 , the size of array is 2 and max index is 1 , and hence IndexOutofBound exception is encountered
use the following loop :
while(a.size()>0)
{
System.out.println("Removed Elements=>"+a.remove(0));
}
whenever you remove an element from arraylist it deletes element at specified location.and this should be noted each time the size of arraylist decreases.
I dont understand what are you trying to remove. If you wan to clear list just call clear() method. If you are trying to remove objects contained in list, than you should know that ArrayList contains objects, not primitive ints. When you add them your are doing the following:
a.add(Integer.valueOf(6));
And there are two remove methods in ArrayList:
remove(Object o) //Removes the first occurrence of the specified element from this list
and the one you are calling:
remove(int index) //Removes the element at the specified position in this list
May be you should call first one:
a.remove(Integer.valueOf(i));

Java - for() loop and arrays

The next question is from test that I've done.. I've run the code on BlueJ and don't get why the return value is 5...
public int mystery(int[] myStuff, int num) {
for (int k = myStuff.length - 1; k >= 0; k--) {
if (myStuff[k] < num) {
return k;
}
}
return -1;
}
myStuff = 2, 4, 0, 1, -6, 3, 8, 7, 5
num = 4
In the test I wrote - 0. Why 5? I don't get it!
What is the part of the
`return -1`
?
You're getting 5 because that is the index of the first element in the array whose value is less than 4 (when starting from the last element and working towards the first). Note that you have:
return k;
...where k is your array index. If you wanted to get the value at that index, you should do:
return myStuff[k];
Here's a simple example that shows that your result is in fact correct: http://ideone.com/7byIY
And the return -1; is just saying "if no elements are less than the specified number then return a value of -1 to indicate that no match was found". This is not an uncommon practice (returning an intentionally chosen, invalid value to indicate that there is no result).
It returns five because that's the index of 3 in your input array, which is the first number strictly smaller than 4 starting from the end of your array.
return -1; would be executed if none of the items in your array satisfy the "strictly smaller than num" criteria.
The function returns the largest index in the array corresponding to a value less than the target. This is accomplished on arbitrary arrays by scanning from the back and returning the first index corresponding to a value less than the target. In your example, 3 < 4 at index 5, so this is the correct answer. If no values smaller than the target are found, -1 is used as a sentinel value to indicate the algorithm failed to find a valid answer.
That function gives the position of the last number in the first argument that's smaller than the second argument (or -1 if all the numbers are larger than the second argument; -1 is a special value with no chance of ambiguity because there's no position -1).
That number is 3 and its position is 5 (starting with 0).
This function just searches for the last value in the array which is greater or equal than num. Let's compute the check myStuff[k] < 4 for all values:
0 1 2 3 4 5 6 7 8 // k
2 4 0 1 -6 3 8 7 5 // myStuff[k]
true false true true true true false false false // myStuff[k] < 4
The last index for which myStuff[k] < 4 is true is obviously 5, so that's the correct answer.
return -1 is needed so that the function returns a value, even if all elements of myStuff are larger than num. For example, with num = -99, the result would be -1.
your return-1 doesn't mean anything for the parameters you have passed here.
as the condition is true for value 3 so it returns the value of k, which is nothing but 5 bt that movement. this is because you are iterating backwards.
mystery(myStuff=[2,4,0,1,-6,3,8,7,5], 4)
then the for begins
for (int k = 8; k>=0; k--)
if ( myStuff[8]=5 < 4) - NO
2nd iteration
k = 7 if (7 < 4) - NO
... so on
k = 6 if (8 < 4) - NO
k = 5 if (3 < 4) - YES - so return k = 5
The last part means:
if myStuff does not have any value < num then it returns -1

identifying .length in two dimensional array

What is the use of .length here? What could be substituted with .length in the code below? I just wanted to understand the code better, Exams tomorrow! W00t!
public class twoDimension{
public static void main(String[] args) {
int[][] a2 = new int[10][5];
for (int i=0; i<a2.length; i++) {
for (int j=0; j<a2[i].length; j++) {
a2[i][j] = i;
System.out.print(" " + a2[i][j]);
}
System.out.println("");
}
}
}
You have declared an array of arrays of int type and initialized it.
10 inside the first square bracket says that you are going to store 10 values for the row and is the size of the array ‘n’ where n=10. The row length is 10.
5 inside the second square bracket says that you are going to store 5 values for the column and is the size of the array ‘n’ where n=5. The column length is 5.
In this case, you have one array with 10 locations
streetX[house_1]
streetX[house_2]
streetX[house_3]
streetX[house_4]
streetX[house_5]
streetX[house_6]
streetX[house_7]
streetX[house_8]
streetX[house_9]
streetX[house_10]
and inside each of the location is another 5 different locations
{house_i[room_number1], house_i[room_number2], house_i[room_number3], house_i[room_number4], house_i[room_number5]}
where i can represent any of 1 to 10
Think of it as 10 houses on a street. Each of the houses having 5 rooms. Each house will have a unique address to distinguish it from other houses on the street. In the same manner, each room in one house will be different from the rest. You can now keep different stuffs in each room.
The street is has an array of houses and each house has an array of room.
Therefore, you will have: You can think of a2 as streetX, i.e. a2 = streetX
streetX has 10 houses, therefore, there are 10 locations in a2. The size of a2 is 10 meaning that the length is 10. Therefore, a2.length = 10
NOTE: When you refer the array values, the index starts from 0 ‘zero’ to ‘n-1′. An array index is always a whole number and it can be a int, short, byte, or char.
house_i (where i ranges from 1 t0 10) but we usually count the index from 0. We'll have index 0 to 9. house_i is similar to a2[i]. There are 5 rooms, hence 5 locations. The size of any a2[i] (i.e. any house a2[0], a2[1], a2[2], a2[3] or a2[4])) is 5 meaning that the length is 5. Therefore, a2[i].length = 5
a2[house1][room1] a2[house1][room2] a2[house1][room3] a2[house1][room4] a2[house1][room5]
a2[house2][room1] a2[house2][room2] a2[house2][room3] a2[house2][room4] a2[house2][room5]
a2[house3][room1] a2[house3][room2] a2[house3][room3] a2[house3][room4] a2[house3][room5]
a2[house4][room1] a2[house4][room2] a2[house4][room3] a2[house4][room4] a2[house4][room5]
a2[house5][room1] a2[house5][room2] a2[house5][room3] a2[house5][room4] a2[house5][room5]
a2[house6][room1] a2[house6][room2] a2[house6][room3] a2[house6][room4] a2[house6][room5]
a2[house7][room1] a2[house7][room2] a2[house7][room3] a2[house7][room4] a2[house7][room5]
a2[house8][room1] a2[house8][room2] a2[house8][room3] a2[house8][room4] a2[house8][room5]
a2[house9][room1] a2[house9][room2] a2[house9][room3] a2[house9][room4] a2[house9][room5]
a2[house10][room1] a2[house10][room2] a2[house10][room3] a2[house10][room4] a2[house10[room5]
NOTE: When you refer the array values, the index starts from 0 ‘zero’ to ‘n-1′. An array index is always a whole number and it can be a int, short, byte, or char.
If n = 10, we'll have 0 ... 9
If n = 5, we'll have 0 ... 4
As an example, streetX[house1][room1] = a2[house1[room1] will become a2[0][0]
Eventually, you will have:
a2[0][0] a2[0][1] a2[0][2] a2[0][3] a2[0][4]
a2[1][0] a2[1][1] a2[1][2] a2[1][3] a2[1][4]
a2[2][0] a2[2][1] a2[2][2] a2[2][3] a2[2][4]
a2[3][0] a2[3][1] a2[3][2] a2[3][3] a2[3][4]
a2[4][0] a2[4][1] a2[4][2] a2[4][3] a2[4][4]
a2[5][0] a2[5][1] a2[5][2] a2[5][3] a2[5][4]
a2[6][0] a2[6][1] a2[6][2] a2[6][3] a2[6][4]
a2[7][0] a2[7][1] a2[7][2] a2[7][3] a2[7][4]
a2[8][0] a2[8][1] a2[8][2] a2[8][3] a2[8][4]
a2[9][0] a2[9][1] a2[9][2] a2[9][3] a2[9][4]
The outer for...loop will be repeated 10 times, remember, a2.length = 10 and the inner for ... loop is repeated 5 times, remember, a2[].length = 5
You initialized a2[i][j] = i, therefore for each inner loop, you will have the index of i (the house) will be the stored as the value or number of things in each room for the house.
Hence, when you execute the program, you will get the output or result below printed out.
Count the number of rows and columns and observe that on each line the values are the same.
0 0 0 0 0
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
6 6 6 6 6
7 7 7 7 7
8 8 8 8 8
9 9 9 9 9
For an array you can use [array_object_name].length or specify the size in number. E.g. a2.length or 10, or a2[i].length or 5 in you example program. Where i equals any of 0, 1, 2, 3, 4. Note that length in .length is a static variable ( You can read more about static variables from here http://download.oracle.com/javase/tutorial/java/nutsandbolts/variables.html and learn about static methods and static classes as well)
In summary, the length is the size of an array
You can learn more about array from here - http://javapapers.com/core-java/java-array/
What is the use of .length here?
no different from one dimensional array: to get number of elements in the array, if you treat two dimensional array as a table, then assuming the first .length is the row length, the second .length is the column length. get it?
What could be substituted with .length in the code below?
What do you see in the declaration (construction to be precise)?
a2.length is the number of rows. In this case the outer loop will iterate 10 times.
a2[i].length is the length of one specific row.

Categories