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
Related
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.
What is the output of the following lines of code? (JAVA)
int nums[] = {1,2,3,4,5,6};
System.out.println(nums[1]+nums[3]);
I'm doing a practise revision sheet but I can't seem to workout the answer to this. EITHER - 7, 4, 5 OR 6.
ALSO when i try to put it into my Eclipse, it doesn't work.
The above code is first declaring an array of integer and then adding the second element (as in programming counting starts from zero), and 4 the element of the array.
If you want to run it on eclipse try this :
`
class Aartest
{
public static void main(String[] atg)
{
int nums[] = {1,32,1,2,31};
System.out.println(nums[1]+nums[3]);
}
}
`
The first line declares an array of integers. An array is a data structure which can hold more than 1 value at a time. To access the values you use indexes. The indexes start from 0. To access a value you write the array name followed by the index of the element in square brackets:
arrayName[index];
Index 0 gives you the first value in the array, index 1 - the second, and so on.
nums[1] will give you the second element in the array - 2.
nums[3] will give you the fourth element in the array - 4.
The second line will print the sum of nums[1] amd nums[3] which is 2 + 4 = 6.
Warning: I am very new to Java and programming in general. I'll try to be as clear as possible.
I am attempting to take a simple integer (inputnumber), convert it to a string (temp), create a new int[] array (numberarray), and loop through this int[] array, starting from the last digit, and print out the name of the digit.
I am rather sure that the conversion from integer to String to int[] array was functional due to Eclipse debugging, but am stumped as to why I am getting an ArrayOutOfBounds message from Eclipse for such a simple for loop. Any clues as to what I am doing wrong is appreciated.
String temp = inputnumber.toString();
int[] numberarray = new int[temp.length()];
for (int i=0;i<temp.length();i++) {
numberarray[i] = temp.charAt(i);
}
for (int i=temp.length();i>0;i--) {
if (numberarray[i]==1) System.out.print("one.");
if (numberarray[i]==2) System.out.print("two.");
if (numberarray[i]==3) System.out.print("three.");
if (numberarray[i]==4) System.out.print("four.");
if (numberarray[i]==5) System.out.print("five.");
if (numberarray[i]==6) System.out.print("six.");
if (numberarray[i]==7) System.out.print("seven.");
if (numberarray[i]==8) System.out.print("eight.");
if (numberarray[i]==9) System.out.print("nine.");
if (numberarray[i]==0) System.out.print("zero");
}
The Eclipse error message I am getting is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at jt.Intermediate8.main(Intermediate8.java:44)
Arrays are 0-indexed in Java. This means the last value is at index NUMBER_OF_ELEMENTS - 1
Therefore, in your for loop, you should change
int i=temp.length() // this is last index + 1 (since we are starting from 0)
To:
int i=temp.length() - 1 // this is last index
Also, as #brso05 said, don't forget to change your loop-ending condition to i>=0 since the last value going backwards will be at index 0.
Your for loop:
for (int i = temp.length(); i >= 0; i--)
You're starting the loop at temp.length(). That's not a valid index. Perhaps you want temp.length()-1?
You should be doing temp.length() - 1. The reason is that the array starts with index 0 not 1 so the last element in an array is stored at the length - 1. If there are 10 elements then 0-9 are your indexes. Also change i>0 to i>=0 if you want to hit all elements.
for (int i=(temp.length() - 1);i>=0;i--) {
My code currently returns the length of the largest substring:
for(int i = 1; i<=l-1;i++)
{
counter = 1;
for(int j = 0; j<i;j++)
{
if(seq[j]<seq[j+1])
{
count[j] = counter++;
}
}
}
for(int i = 0;i<l-1;i++)
{
if(largest < count[i+1])
{
largest = count[i+1];
}
}
assuming seq is the numbers in the sequence. So if the sequence is: 5;3;4;8;6;7, it prints out 4. However, I would like it to also print out 3;4;6;7 which is the longest subsisting in ascending order.
I am trying to get the length of the largest sub sequence itself and the actual sequence, but I already have length..
My instinct is to store each number in the array, while it is working out the count, with the count. So returning the longest count, can also return the array attatched to it. I think this can be done with hashtables, but I'm not sure how to use those.
I am just looking for a hint, not the answer.
Thanks
You need to implement a dynamic programming algorithm for the longest ascending subsequence. The idea is to store a pair of values for each position i:
The length of the longest ascending subsequence that ends at position i
The index of the item preceding the current one in such ascending subsequence, or -1 if all prior numbers are greater than or equal to the current one.
You can easily build both these arrays by setting the first pair to {Length=1, Prior=-1}, walking the array in ascending order, and looking for the "best" predecessor for the current item at index i. The predecessor must fit these two conditions:
It must have lower index and be smaller than the item at i, and
It must end an ascending subsequence of length greater than the one that you have found so far.
Here is how the data would look for your sequence:
Index: 0 1 2 3 4 5
Value: 5 3 4 8 6 7
------------ ----------------
Length: 1 1 2 3 3 4
Predecessor: -1 -1 1 2 2 4
Once you finish the run, find the max value among lengths array, and chain it back to the beginning using the predecessor's indexes until you hit -1.
Why does this cause an array out of bounds exception ?
x[10][2] = 5;
Should this be assigning the 3rd spot of the 11th array, the value 5
I thought of it in a rectangular way.
Its like we have to count 11 rows(representing the 10 arrays)
and then we have to go to the 3rd column that is the 2
OR
I should be looking at it as an array looking for the 11th spot in an array of size 2 that doesn't actually exist ?
Is the 11th element of x an array? If it is, what is its length?
You are receiving that error because it's likely the length of that element is less than 3.
Test it by trying
System.out.printf(x[10].length);
Hope that helps.
Why does this cause an array out of bounds exception?
x[10][2] = 5;
This only happens when you try to access a position out of the range that you had defined for your array. For example
int x[20][20];
You can make x[10][2] = 5; without a problem because 10 < 20 and 2 < 20. But if you did:
x[30][20] = 5;
You would have the out of bounds exception because you are trying to access the position (30,20) of the 2D array, a position that surpasses the size of the 2D array.
It is because x[10][2] does not exist.
It can be either because x[10] is not a valid element (i.e. x.length is equal to or greater than 10), or x[10][2] is not a valid element (i.e. x[10].length is equal to or greater than 2). The exception message tells you which index fails, if they differ.
Note that a multidimensional array doesn't have to be a matrix. This is called a jagged array.
For example, consider the following code (from Wikipedia):
int[][] arr = new int[2][]; // creates 2 rows
arr[0] = new int[3]; // 3 columns for row 0
arr[1] = new int[5]; // create 5 columns for row 1
Referencing arr[0][4] would throw an ArrayIndexOutOfBoundsException, while referencing arr[1][4] would not.
As Mark Stevens already mentioned in the comments, which one is the row and which one the column, is subjective. As opposed to what jazzbassrob says in the comments, Java has neither row-major nor column-major order. In fact, in Java, there is no such thing as a two-dimensional array, instead, it's actually an array of arrays.