Batoulz
Batoulz

Reputation: 45

while loop with semicolon java

Why do we use while loop with a semicolon (;) just after it?

I have this code as an example:

public static void Register()
{String name,code;
int posStudent,posCourse;
System.out.println("-----------------------------------------------");
System.out.println("Enter the name of the student");
name=in.next();

while ((posStudent=VerifyTheStudentName(name))==-1);

System.out.println("-----------------------------------------------");
System.out.println("The list of available courses is:");
for(int i=0;i<courses.size();i++)
    System.out.println(courses.get(i));
System.out.println("-----------------------------------------------");
System.out.println("Enter the course code");
code=in.next();
while((posCourse=VerifyTheCourseCode(code))==-1);
students.get(posStudent).registerTo(courses.get(posCourse));
}

so what does while do here?

Upvotes: 1

Views: 3040

Answers (2)

Stephen C
Stephen C

Reputation: 719259

A while or for loop with a semicolon after it is a loop with an empty body. All of the work is done by the loop condition logic / iteration logic. So

    while ((posStudent = verifyTheStudentName(name)) == -1);

is equivalent to

    while ((posStudent = verifyTheStudentName(name)) == -1) {
    }

Please don't write loops with empty bodies the first way. It is so easy for the reader to not notice the semicolon and think that the statement after it is supposed to be the loop body.

So, what does the statement mean?

  1. Loop while verifyTheStudentName(name) returns -1.
  2. When some other value is returned, capture it in posStudent.

Capturing the value in a conditional like this is a fairly common idiom ...

However, there are reasons to suspect that this example code might be incorrect. (If you repeatedly call the same function on the same argument, you would expect to get the same result each time, leading to a potential infinite loop. But it does depend on the context ...)

Upvotes: 3

AswinRajaram
AswinRajaram

Reputation: 1632

In case the while condition does all the "work",no loop body is needed.

Upvotes: 5

Related Questions