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.
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.
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.
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!
Does anyone knows what the group_skip do?
Maybe it is a basic programming, but I've been programming using Java for some years and just found it today.
group_skip: do {
event = stepToNextEvent(FormController.STEP_OVER_GROUP);
switch (event) {
case FormEntryController.EVENT_QUESTION:
case FormEntryController.EVENT_END_OF_FORM:
break group_skip;
}
} while (event != FormEntryController.EVENT_END_OF_FORM);
Thanks!
This is a labelled loop, when break group_skip; statement is executed, it will jump out of the do while loop which is labelled as group_skip
boolean isTrue = true;
outer: for (int i = 0; i < 5; i++) {
while (isTrue) {
System.out.println("Hello");
break outer;
} // end of inner while
System.out.println("Outer loop"); // does not print
} // end of outer loop
System.out.println("Good Bye");
This outputs
Hello
Good Bye
You can get the concept clear here.
There is a labelled for loop called outer and there is inner while loop
When inner for loop is being executed, it encounters break outer; statement
The outer for loop has a System.out.println"Outer loop" statement but that does not get printed.
This is because break outer causes the control to jump out of labelled for loop directly
Now this example for continue statement
outer: for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.println("Hello");
continue outer;
} // end of inner loop
System.out.println("outer"); // this won't print
} // end of outer loop
System.out.println("Good bye");
This prints
Hello
Hello
Hello
Hello
Hello
Good bye
There is a labelled for loop here and an inner for loop
Inner for loop prints Hello and continues to the outer loop.
Because of this, the statements below inner for loop are skipped and outer loop continues to execute.
At the end of outer for loop, Good Bye is printed
Hope this makes everything clear.
group_skip is a label. Labels allow you to break or continue specific loops when you've got them nested.
Here's what Oracle has to say on the subject.
when ever we use simple break statement then we can only transfer control from inner most loop to the outer most (if we have nesting of loops). for exampel
for(int i=0; i < 10; i++){
if(i==5){
break;
}
}
statement x;
will simply transfer the control to statement x. But if you use it inside nested loops then it will work differently.
for(int i=0; i < 10; i++){
for(int j=0; j < 10; j++)
if(i==5){
break;
}
}
statement y;
}
statement x;
in this case it will send the control to statement y. If you want to send the control from innermost loop to either outermost loop or outside the loop then you need such a break statements with labels. Just do it from your self and you will see interesting output.. :)
group_skip is a label used for things like break. (Also goto and jump in other languages)
In java specifically it would be used to break from a code block identified by the label, behaving just like a break statement in a while loop, except breaking from a labeled code block.
Here is some more discussion on the topic
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to Break from main/outer loop in a double/nested loop?
I have the following situation:
for(int i = 0; i < schiffe.length-1; i++){
if(schiffe[i].schaden){
schlepper.fliege(schiffe[i].x,
schiffe[i].y,
schiffe[i].z);
schlepper.wirdAbgeschleppt = schiffe[i];
for(int k = 0; k < stationen.length-1; k++){
if(stationen[k].reparatur == null){
schlepper.fliege(stationen[k].x,
stationen[k].y,
stationen[k].z);
break;
}
}
}
}
I want to
schlepper.fliege(stationen[k].x,
stationen[k].y,
stationen[k].z);
be performed once and then break out of the inner loop and continue with the for(int i... loop. So I used a break in my code. But I am not really sure if this is right. Does the break cause a break for all loops or just for the second loop?
It breaks only the inner loop, and therefore does what you want. To break more than one level, in Java, you can use a "labelled break" like so:
schiffe_loop:
for(int i = 0; i < schiffe.length-1; i++){
some_stuff();
for(int k = 0; k < stationen.length-1; k++){
if (something_really_bad_happened()) {
break schiffe_loop;
}
}
}
But usually you will not need this.
You may consider making a separate method for the inner loop anyway; it's something you can easily give a name to ("find_available_station" or something like that), and will probably need somewhere else.
Also, please be aware that your loops right now will miss the last element of each array. Think carefully about why you are using < instead of <=; it's exactly so that you use every value from 0 up to but not including the specified one.
break will break the innermost loop, in your case 2nd loop.
To make it break the outer loop you can use a labeled break as:
OUTER:for(...) {
for(...) {
break OUTER;
}
}
break only breaks out of the innermost loop.
break will cause break for closest loop only (second loop)
Just the second one. You can use "goto" of course.
Break statement terminates the closest enclosing loop or switch statement in which it appears in many languages but you can try it and be sure 100%.
put the inner two loops in a function and use return to break out of both of them.
If you need more control, you can use a labeled break. More info here. As others have said, break will close the closest loop.
What about using a boolean you call 'found' and use it like this:
while(!found) {
for(...) {
//todo
}
}
I Think You Can Do One More Thing..
for(int k = 0; k < stationen.length-1; k++){
if(stationen[k].reparatur == null){
schlepper.fliege(stationen[k].x,
stationen[k].y,
stationen[k].z);
k = stationen.length + 1 ;
}
}