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.
Related
I'm just getting started so this is going to be a beginner question :)
I've had this lesson but there is something in the code I don't understand.
int[] values;
values = new int[3];
values[0] = 10;
values[1] = 20;
values[2] = 30;
System.out.println(values[0]);
System.out.println(values[1]);
System.out.println(values[2]);
This is the basic array lesson I understand. But he said that there is another way to print out the values. By using a for loop.
for(int i=0; i<values.length; i++)
System.out.println(values[i])
This is the part I don't understand.
What is values.length? Is it 3 or 2?
Why doesn't it print out the values more than once?
Thnx
Since arrays in Java are zero-indexed, so an array that has [10, 20, 30] i.e. 10 at index 0, 20 at index 1, and 30 at index 2, has a length of 3. Simply the length is the number of elements in the array.
Now regarding why there is a single print statement here, it might be easier to visualise what the loop does.
The loop simply executes the code inside it, every time with a new value of i, as long as the loop condition is met.
So yo can think of this
for(int i=0; i<values.length; i++)
System.out.println(values[i])
to be translated to this
System.out.println(values[0])
System.out.println(values[1])
System.out.println(values[2])
But because as you can notice, the same function is used multiple times, only with a different input, we can only write the function once, and run it multiple times with different inputs through a loop.
On a side note, you should almost always use a BLOCK with a for statement, even if it only has one line within it.
So instead of:
for(int i=0; i<values.length; i++)
System.out.println(values[i]);
You'd do:
for(int i=0; i<values.length; i++)
{
System.out.println(values[i]);
}
By default, a for loop only runs the line immediately following it inside the loop. The indentation is merely aesthetic. If you want more than one line to be run, then you'd include them all within the brackets.
Many beginners skip the brackets and then later add a line to it...looking something like below, but expecting both lines to be run within the loop:
for(int i=0; i<values.length; i++)
System.out.println("Value: "); // only this line is within the loop
System.out.println(values[i]); // this line is simply indented, and stands alone
You can avoid some lost time troubleshooting weird problems from code like above by starting with good habits and always add brackets to your for loops.
This question already has answers here:
Having issue with the concept of extra semi-colon at the end of for loop in Java
(5 answers)
Closed last month.
When I am doing my assignments I done a small mistake by placing ; in the for loop like the following code.
for(i=0;i<n;i++);{
n=n*i;
}
When I compiled the program its compiled with no error but I did not get the output for a while. Then later figured out that I misplaced the semicolon in for loop. What was the bug when I place semicolon after for loop.
class A
{
public static void main(String args[])
{
int i, n=1;
for(i=1; i<=5; i++);
n=n*i;
System.out.println(n);
}
}
I am getting output for the following code as 6 instead of 120.
When you do this: for(i=0;i<n;i++); you are essentially doing this: for(i=0;i<n;i++) {}. This translates to a loop with no body.
This also happens for while loops: while(..);{<Foo>}. The extra ; will make execute only once.
The same goes for if statements. Doing if(a==b);{<Foo>} will still execute <Foo> for the same reason. If a == b, then, the empty statement will be taken into consideration. Afterwards, <Foo> will be executed. This can give the wrong impression that Java will treat a false as a true since if a != b, then, <Foo> would still be executed.
for loop can execute only one code block or one statement, even empty ones. So semicolon here represents empty statement (statement which does nothing).
In other words you can think of for(int i; i<n; i++); as for(int i; i<n; i++){}.
So code like
for(int i; i<n; i++);{
foo();
}
is same as
for(int i; i<n; i++){
//do nothing, except i++
}
//after loop finishes
{
foo();
}
and
for(int i; i<n; i++);
foo();
is simply
for(int i; i<n; i++){
}
foo();
About
int i, n=1;
for(i=1; i<=5; i++);
n=n*i;
System.out.println(n);
I am getting output for the following code as 6 instead of 120.
As explained earlier your code
for(i=1; i<=5; i++);
n=n*i;
is same as
for(i=1; i<=5; i++){}
n=n*i;
which means that it your loop will not execute n=n*i but will try to execute {} which does nothing. Also at end of each iteration i will be incremented because of i++ so when i will become 5 your and i<5 will be false flow of control will leave loop and will execute n=n*5 which means that n will become n=1*5 which is 5.
If you want to get as result 120 by executing n=n*i in each loop simply remove semicolon after loop.
for(i=1; i<=5; i++)//<--removed semicolon
n=n*i;
BTW prefer to place code which should be executed by loop or if statement in code blocks,
for(i=1; i<=5; i++){
n=n*i;
}
This makes your code easier to read and maintain. Also if you will make again your mistake and you will use some auto formatting tool which will indent your code for you you will see that it will be formatted as
for(i=1; i<=5; i++)
;
{
n=n*i;
}
which makes spotting such errors very easy.
If you place semicolon after a for loop then it is technically correct syntax. Because it is considered as an empty statement - that means nothing to execute.
In your case -
for(i=0;i<n;i++);
An empty statement executed up to n times. Or in other words the for-loop simply runs n times.
The curly braces {} after the for loop executed only once. Now the code block inside the curly braces {} considered as a floating block.
You didn't get an output because the semi-colon ended the statement, [ for(I = 0; I < n; I++ ]
The code should be:
for(i=0;i<n;i++) {
n=n*1;
}
The reason why you're getting 6 is simple. At the last iteration the value of i turns from 5 to 6, the loop won't do another iteration because i=6 and it doesn't satisfy the condition for the for loop any more. Since n=1 and i=6 then the output of n*i is 6.
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
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
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!