Java for loop gets skipped - my mistake? - java

I have already some c# knowledge but I'm really confused by such an easy thing, but maybe the problem is deeper than I expect. I imported a "little game" for learning java and wrote that code:
import de.ur.mi.bouncer.apps.BouncerApp;
public class DasErsteHindernis extends BouncerApp {
#Override
public void bounce() {
loadMap("Obstacles");
runtillwall();
climbupwards();
}
private void runtillwall(){
while(bouncer.canMoveForward() == true){
bouncer.move();
}
}
private void climbupwards(){
bouncer.turnLeft();
bouncer.move();
for(int i = 0; i==2; i++){
bouncer.turnLeft();
}
}
But the for loop gets skipped -> the bouncer doesn't turn left. What did I do wrong?

The middle part of a for loop is a condition. Yours is saying while i is equal to 2, do this. It never gets to two, so it never executes. You should be using the less-than or less-than-or-equal-to sign. (< <=)

for(int i = 0; i==2; i++){
Here you are initializing i with 0,so first when loop starts i is 0 ,then middle part which is condition in your loop that should be true for loop to start.In your case,you are saying if i is equal to 2 then execute the instruction.It fails and your loop body is not executed single time.
it seems you need
for(int i = 0; i<=2; i++){
This one will execute loop body 3 times.
See Also
for loop in Java

Related

Nothing is being output to the console! (Java, Eclipse Mars)

So basically I am experimenting with writing a path finding program that find a path from some point in a 10*10 grid to another, that is fine.
I have a class Path that is an ArrayList of GridSquares (which are just glorified co-ordinates).
I have written a small method within the Path class to display the path, and this is where the problem, which is so minor but so very infuriating, arises.
When I try to run the code, and call displayPath, nothing is output to the console and the program terminates with no errors.
Here is the code for displayPath:
public void displayPath(){
System.out.println("This is displayPrint"); //This line is included to make sure the program calls the method correctly.
for(int i=1; i==10; i++){
for(int j=1; j==10; j++){
if(this.includesSquare(i, j)){
System.out.print("[x]");
} else {
System.out.print("[ ]");
}
}
System.out.print("\n");
}
}
I included the first line to ensure that the console/System.out.print() was working correctly and this gets displayed every time the method is called.
Here is the code for includesSquare:
public boolean includesSquare(int x, int y){
for(GridSquare square : this.path){
if(square.getX()==x && square.getY()==y){
return true;
}
}
return false;
}
I have uninstalled and re-installed Eclipse, copied the java files into a new project ect and nothing seems to make any difference. I know the console is working fine as it displays the first line of displayPath correctly.
Any help is greatly appreciated!
for(int i=1; i==10; i++) and for(int j=1; j==10; j++) will not work.
The middle condition (i==10) is supposed to say when the loop is supposed to be executed. As it is, you are saying you only want the loop to execute when i is equal to 10. Since i is initially equal to 1, it will skip right over the loop.
What you will likely want is
for(int i=1; i<10; i++)
This way, when i is equal to 1, it satisfies the condition that it is less than 10, so the loop will get executed and i will increment. This will keep happening until i is equal to 10, at which point the condition i<10 fails, so the loop will exit.
In less words, you want your condition to say "loop while this is true" as opposed to "loop until this is true".
for(int i=1; i==10; i++){ is where your problem lies.
The syntax for the for loop is as follows:
for(<initial condition>; <checking condition>; <incrementing>)
So what you have is
Staring from i = 1, increment by 1 while i == 10. Well since i starts at 1, you've already failed at the first step!
Turn your for loop into while loop to understand this better:
int i = 1;
while(i == 10) {
doSomething();
i++;
}
So of course that won't work.

Java program won't finish method - exits after a for loop with no errors instead

edit: As I was writing this post, I made my code simpler (lost arrays entirely) and got it working. Yet I am still not sure why this specific code won't work, so I'll keep the question.
Hello.
I am writing a small puzzle game in Java (using Eclipse 4.4.2) and stumbled upon a problem inside one of my methods. Basically - it won't complete the method, it just exits the method after the for loop is done without any warnings or errors (I'm not catching exceptions either). I hope I missed something simple..
Details:
I have a method to set the colors of an object and up to 5 other objects that are linked to it through lines. I set up the color of the main object, then find the linked objects through for-loops and in the end change their colors as well. (Double checked the code for Lines, there are simple return methods and nestA and nestB as data - no problem there). lines is an array with a length of 50, nests as its members.
Here's the code:
public void highlightNests(Nest nest) {
//setting the color of the main object (a nest).
Mappers.setColor(nest, nestHighlight);
//resetting the array. Temp solution, had a return method earlier,
//this is part of the debugging.
connectedNests = null;
connectedNests = new Nest[5];
int i = 0;
Gdx.app.log("highlightNests()", "starting the loop");
for (int j=0; j<lines.length; j++) {
if (lines[j].getNestA() == nest) {
connectedNests[i] = lines[j].getNestB();
i++;
}
if (lines[j].getNestB() == nest) {
connectedNests[i] = lines[j].getNestA();
i++;
}
}
//This is where the program exits the method. The following
//lines are not run.
Gdx.app.log("highlightNests()", "entering loop");
for (int l=0; i<connectedNests.length; l++) {
Mappers.setColor(connectedNests[l], nestHighlight);
Gdx.app.log("highlightNests", "set color");
}
}
Deleting the middle section makes the end part run, so there are no errors in the last part.
Your second loop is completely wrong, you declare the counter as l and increment another counter i, you should use l<connectedNests.length change it like this:
for (int l=0; l<connectedNests.length; l++) {
Mappers.setColor(connectedNests[l], nestHighlight);
Gdx.app.log("highlightNests", "set color");
}
And the program won't finish method and exits before the loop because, it doesn't even enter the loop as it's incorrect.
You have to use l instead of i in condition like,
for (int l=0; l<connectedNests.length; l++)...
//---------^ l not i

Printing to Console Does Nothing in For Loops

I've tried several programs that involve printing to the console in for loops, but none of them have printed anything. I can't work out the problem, and I've boiled it down as simply as possible here:
for (int x=0; x==10; x++)
{
System.out.print("Test");
}
Like I said, absolutely nothing is printed to the console. Things outside of the for loop will print, and things affected by the for loop will print.
Perhaps it's something very simple, but I wouldn't know considering I'm relatively new to programming and Eclipse gives me no errors. Any help would be much appreciated, as this is plaguing my class files at the moment.
Thanks,
Daniel
Your for loop condition is wrong. You want the condition to be true to continue looping, and false to stop.
Try
for (int x=0; x < 10; x++)
For more information, here's the Java tutorial on for loops.
#rgettman gave the reason your code didn't work above.
The way the for loop works is in the brackets the first variable is where the loop starts (i.e. 'x=0'), the second variable is the condition (i.e. 'x<= 10'), and the third is what to do for each loop (i.e. 'x++').
You had "x==10" for the condition, so for the first scenario where x was equal to "0", the loop ended because it was NOT equal to "10". So you want it to be "x<=10" (x is less than or equal to 10); this will go through 11 loops.
rgettman is completely correct. A for loop should be used as so:
for is a type of loop in java that will take three parameters separated by semicolons ;
The first parameter will take a variable such as int i = 0; to create a simple integer at 0.
The second parameter will take a condition such as i < 10, to say while the i integer is less than
The third and final parameter will take an incrementing value like, i++, i--, i +=5, or something to that effect.
This part should like like for(int i = 0; i < 10; i++) so far.
Now you need the brackets { and }. Inside of the brackets you will perform an action. Like you wanted to print "test" to the console.
for(int i = 0; i < 10; i++) {
System.out.println("test");
}
This would print "test" 10 times into the console. If you wanted to see what number i was at, you could simply say,
for(int i = 0; i < 10; i++) {
System.out.println(i); // Current value of i
}
Hope this was of use to you!

Java - Game : Multiple instances

I'm trying to make a game in Java, and I've got already something. But i want to make the Player shoot bullets.
I've came up with the idea to make an object array, and put all the Bullet instances into the array. then in a thread, I want to make them all move(all the objects in the array).
This is what I put in the main class:
Bullet[] BulletArray;
public int Bullets = 0;
public void run() {
for(int i = 0; i < Bullets; i++){
BulletArray[i].Step();
}
if(Key.FireKey){
BulletArray[Bullets + 1] = new Bullet();
Bullets += 1;
}
}
I've just included the basic stuff, i.e. The run function runs fine, in the original code.
The code doesn't work, it gives me an error when I press Fire. The error is somewhere at
BulletArray[Bullets + 1] = new Bullet();
I hope you understand what I mean.
Well, for starters, your BulletArray is never initialized.
When you enter run(), your for() loop appears to work fine because it does not actually enter the block. Your int i = 0 is declared and is already greater than or equal to your limit, which is the int Bullet = 0. This means that the body of the loop never executes.
Then, when you press the Key.FireKey, it attempts to reference an array index that doesn't exist. It can't exist, because the array has never been initialized.
To initialize your array, you will need to do something more like this:
private int maxBullets = 10;
Bullet[] bulletArray = new Bullet[maxBullets];
Then your for() loop will actually enter. Note that in your Key.FireKey block, however, that you will have to perform some checking to make sure that you don't get an IndexOutOfBoundsException by trying to fire more bullets than you've created. i.e.,
if(Key.FireKey) {
if(bullets < maxBullets) {
bulletArray[++bullets] = new Bullet();
}
}

iterator for loops with break

let say my code look like below
for(..)
for(..)
for(..){
break; //this will break out from the most inner loop OR all 3 iterated loops?
}
Your example will break out of the innermost loop only. However, using a labeled break statement, you can do this:
outer:
for(..)
for(..)
for(..){
break outer; //this will break out from all three loops
}
This will only break out from the inner loop. You can also define a scope to break out from. More from the language specs:
A break statement with no label
attempts to transfer control to the
innermost enclosing switch, while, do,
or for statement of the immediately
enclosing method or initializer block;
this statement, which is called the
break target, then immediately
completes normally.
Yes, without labels it will break only the most inner loop.
Instead of using labels you can put your loops in a seperated function and return from the function.
class Loop {
public void loopForXx() {
untilXx();
}
private void untilXx() {
for()
for()
for()
if(xx)
return;
}
}
From the most inner loop :)
int i,j,k;
for(i = 0; i < 2; i++)
for(j = 0; j < 2; j++)
for(k = 0; k < 2; k++)
{
printf("%d %d %d\n", i, j, k);
break;
}
Will produce :
0 0 0
0 1 0
1 0 0
1 1 0
You should take a look here: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/branch.html
as often mentioned i don't like to break with a label eather. so while in a for loop most of the time i'm adding a boolean varible to simple exit the loop.. (only if i want to break it of cause;))
boolean exit = false;
for (int i = 0; i < 10 && !exit; i++) {
for (int j = 0; j < 10 && !exit; j++) {
exit = true;
}
}
this is in my opinion more elegant than a break..
Many people here don't like labels and breaking. This technique can be compared to using a 'goto' statement, a flow control statement which allows jumping out of a block of code in a non-standard way, obliviating use of pre- and post conditions. Edsger Dijkstra published a famous article in Communications of the ACM, march 1968, 'Goto statement considered harmful' (it's a short read).
Using the same reasoning presented in the article, returning from inside an iteration as suggested by TimW is also bad practice. If one is strict, to create readable code, with predictable entry- and exit points, one should initialize the variable which will hold the return value (if any) at the beginning of the method and return only at the end of a mehod.
This poses a challenge when using an iteration to perform a lookup. To avoid using break or return one inevitably ends up with a while-loop with a regular stop condition and some boolean variable to indicate that the lookup has succeeded:
boolean targetFound = false;
int i = 0;
while (i < values.size() && ! targetFound ) {
if (values.get(i).equals(targetValue)) {
targetFound = true;
}
}
if (!targetFound) {
// handle lookup failure
}
Ok, this works, but it seems a bit clunky to me. First of all I have to introduce a boolean to detect lookup success. Secondly I have to explicitly check targetFound after the loop to handle lookup failure.
I sometimes use this solution, which I think is more concise and readable:
lookup: {
for(Value value : values) {
if (value.equals(targetValue)) {
break lookup;
}
}
// handle lookup failure here
}
I think breaking (no pun intended) the rule here results in better code.
it will breake from most inner loop,
if you want to break from all, you can hold a variable and change its value when you want to break, then control it at the beginning of each for loop

Categories