We've started using netbeans in our Java programming class, after using notepad++ for a while. While iterating through an array list. I used the following code:
for (int i=0; i<=randomarrayhere.length; i++)
Netbeans suggested to flip the position of i and array.length
for (int i=0; randomarrayhere.length>i; i++)
What do we gain by this?
Thanks!
The first would throw an ArrayIndexOutOfBoundsException when i reaches randomarrayhere.length.
Aside from that (if you use i<randomarrayhere.length), there is no difference.
you can either use randomarrayhere.length>i or i<randomarrayhere.length, but don't use randomarrayhere.length>=i or i<=randomarrayhere.length because if you call randomarrayhere[i] anywhere in your forloop you will get an Exception since array indices are zero-based.
An array with 1 item has a length of 1, but the objects index in the array is 0. This throws an index out of bounds error. You can also do x=array.length - 1 and use = in your comparison
Related
I am trying to make a little game on my own to get used to Java and I just had a problem with LinkedList Index. I found a way to patch my problem but I still don't understand why my first solution is not working. This code:
for (int i=0; i <= PlanetList.size(); i++)
{
g.drawImage(PlanetList.get(i).planetImage, PlanetList.get(i).xPos, PlanetList.get(i).yPos);
}
Gave me a java.lang.IndexOutOfBoundsException but this code:
for (int i=1; i <= PlanetList.size(); i++)
{
g.drawImage(PlanetList.get(i-1).planetImage, PlanetList.get(i-1).xPos, PlanetList.get(i-1).yPos);
}
The thing is ... my index start at 0 in both case. Why does the first gives me an Error?
Your last index in the first example is going above the allowed index range. For e.g., if the size of the list is 10, the allowed index range is [0 9]. In your first loop, it goes up to 10 (i <= PlanetList.size()). Change the terminal condition to i < PlanetList.size() to fix your issue.
The alternate is to use no indices to access elements in your list as #GhostCat has suggested:
for (Planet planet : PlanetList) {
g.drawImage(planet.planetImage, planet.xPos, planet.yPos);
}
This is called for-each loop in Java
The other solution is to simply use the index-free version to iterate "collections" that was introduced years ago:
for (Planet planet : PlanetList) {
g.drawImage(planet.planetImage, planet.xPos, planet.yPos);
As a nice side effect, that also eliminates the code duplication that you had in your example.
And while we are at it: you are somehow violating the "tell dont ask" principle. Meaning: you are asking your planet object to give all the details you need to draw it. In good Object Oriented designs, you avoid that. Instead, you tell objects to do something. In other words: you could change your planet class to
public void drawWith(Graphics g) { ...
With that the above code can be rewritten as:
for (Planet planet : ... ) {
planet.drawWith(g);
YOU are getting the Out of bounds error because the variable i declared in the for loop is running for less than equal to condition of planetlist size as i starts from zero it will go till the linked list size but since you have given less than equal to it goes in the loop one more time therefore out of bounds exception .Just change the for loop condition to i less than linked list size it will work
I am trying to find on a Vector how many indexes start with a given letter or number.
I've tried vector.indexOf("A"); and vector.lastIndexOf("A"); but of course they are "useless" for what I am trying to do because those try to find a position that only have "A" and nothing else.
I wanted to know if there is a Java method to do this or if I need to do it "by myself", if so, a little guiding on the how-to process would be thanked.
If you do not want to (or can) use streams or lambdas you can also use this little loop here:
int count=0;
for (int i = 0; i < vec.size(); i++) {
count = vec.get(i).charAt(0)=='A' ? count+1 : count;
}
No big thing, just checking each element if it starts with A and then counting up.
In Java8 you can use Streams to access functional-style operations such as filter() and count(). Use the stream() method to get a Stream on your collection.
For example lets say I've create a single dimensional array and initiate the array to 100. If I want to be able to use all the values of the array, like in a for loop, how would I do it? I found two methods below but I'm not sure which approach is recommended. Also is there any differences at all?
int[] list = new int[100];
for (int i = 0; i < list.length; i++)
or
for (int i = 0; i < 100; i++)
Which of these two syntax is more commonly used?
This is much better:
for (int i = 0; i < list.length; i++)
If you change your mind, and decide that the list needs to be of length 150 instead, then the rest of your code will still work.
The other option requires you to change all of your for loops if you change the length of the array at all.
There aren't really any other differences.
EDIT: As Manoj Sharma mentioned in his answer, there's another thing you can do:
for (int myInt : list)
This will do the iteration for you, but you can't get the index in the loop.
I'm mentioning this for completeness, but if you found this helpful, upvote his answer!
for (int i = 0; i < list.length; i++) It is dynamic condition handling, It will change according to your array length.
for (int i = 0; i < 100; i++) It is static condition handling, If you have thousands of for loop you need to change each loop condition.
Evey time make sure that you avoid hard coding in your application.
Well above answer given by #Anubian Noob is good. but java5 onward java provides enhanced for each loop which is far better than other. Even no error chance in this method. look below:
for(int i: list){
System.out.println(i);
}
this will loop through the entire array and display all the element store in an array. you can also use this method for multi dimensional array too.
It is better to store the length of the array in a variable and then use it. Instead of hard coding it in the loop or find it every time loop runs.
var arraySize = yourArray.length;
for(i;i<arraySize; i++){
//your code here.
}
In Java 8 you are much better off learning to use streams. They are more intuitive and you don't need to worry about anything like the size.
For example:
int list[] = {4, 7, 3, 9, 11};
Arrays.stream(list)...
In this case Arrays.stream knows that you have created an IntStream so you get max, min, sorted, sum etc.
You need for loop much less frequently now.
I'm a novice programmer. This may be a simple problem but I've never seen this before. First of all, let me clarify that I'm not even trying to manipulate the index. Here's the part of the code that is causing the exception:
int[] bumpercatcher = new int[4];
//time variable that helps control events
int time = 0;
public void setup()
{
bumpercatcher[0]=4;
bumpercatcher[1]=4;
bumpercatcher[2]=4;
bumpercatcher[3]=4;
As you can see I'm trying to set them all equal to 4 at the start of the program. This causes the arrayindexoutofbounds exception. If I set them all equal to 0~3 then there is no problem (until I set them to a value greater than 3 later in the program). I don't understand it.
-it doesn't matter if I set the array size to 10, I still get the same exception
-it doesn't matter if I set only one of the values (i.e. at index 1, which is definitely within bounds of the array). same exception
Is there something I'm doing wrong? Thanks.
well, here' the entire code if you want to take a look(not too long, 1 class, bad programming practies): http://dl.dropbox.com/u/33501308/Pong.java
Here's the html from which you can see the program from (not much to see. it just freezes instantly.): http://dl.dropbox.com/u/33501308/bin.zip
by the way I'm using eclipse.
I don't really know what SSCEE is. sorry
Your posted code file includes loops along the lines of
for(int j: bumpercatcher) {
if(bumpercatcher[j]>5)
...
}
This is an issue. This is a different kind of loop than a traditional for loop. It is an extended or enhanced for, also called a foreach. It reads "for each integer j in array bumpercatcher do x." You are taking your element j (a value) and using it as an index to the array. When your value exceeds the maximum index, you will get an exception.
Write your code with a proper for loop if you want to access by index, or try simply restructuring your logic like
for (int j : bumpercatcher) {
if (j > 5) // j is the value!
...
}
I'm not sure what the problem is, but a far more readable way of doing this would be with a for loop:
for(int i = 0; i < bumpercatcher.length; i++) {
bumpercatcher[i] = 4;
}
Basically, I am trying this, but this only leaves array filled with zeros. I know how to fill it with normal for loop such as
for (int i = 0; i < array.length; i++)
but why is my variant is not working? Any help would be appreciated.
char[][] array = new char[x][y];
for (char[] row : array)
for (char element : row)
element = '~';
Thirler has explained why this doesn't work. However, you can use Arrays.fill to help you initialize the arrays:
char[][] array = new char[10][10];
for (char[] row : array)
Arrays.fill(row, '~');
From the Sun Java Docs:
So when should you use the for-each loop?
Any time you can. It really beautifies your code. Unfortunately, you cannot use it everywhere. Consider, for example, the expurgate method. The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it.
This is because the element char is not a pointer to the memory location inside the array, it is a copy of the character, so changing it will only change the copy. So you can only use this form when referring to arrays and objects (not simple types).
The assignment merely alters the local variable element.