Is there ever a situation where you must use a do while loop? Is it an accepted practice? It seems like it is equivalent to a plain while loop except that its first iteration happens before checking the conditional, if that is even true.
int i = 3;
while ( i > 0 ) { // runs 3 times
i--;
}
vs
int j = 3;
do {
j --;
} while ( j > 0 ); // runs 3 times
The same?
EDIT: I have seen the java doc, but
the example in the java docs doesn't look like it requires that the particular routine inside of the do while loop must be run in the do while loop instead of inside of a regular while loop!
Is there ever a situation where you must use a do while loop?
No: every do-while loop can be written as a while-loop by running the body once before the loop begins. However, there are certainly cases where it makes more sense to use the do-while construct (i.e. if you always want the loop to iterate at least once), which is why it exists in the first place.
Is it an accepted practice?
If you use it appropriately, then yes absolutely.
It seems like it is equivalent to a plain while loop except that its first iteration happens before checking the conditional, if that is even true.
That's right. You can read more about do-while in its tutorial.
This example maybe help you be clearer:
int i = 3;
System.out.print("while: ");
while (--i > 0){
System.out.print("x");
}
System.out.print("\ndo-while: ");
int j = 3;
do
{
System.out.print("x");
}while (--j > 0);
This prints
while: xx
do-while: xxx
A real time example.
There is a contest with 5 level.
In each level if you score 100 you can proceed to next level.
Less code for do while, but not for while.
boolean playContest()
{//do while
int level = 1;
int score;
do
{
score = 0;
score = play();
}while(score>99 && level++<6)
if(level>4 && score>99)
isWinner = true;
else
isWinner = false;
return isWinner;
}
boolean playContest()
{//while
int level = 1;
int score;
while(level <6)
{
score = 0;
score = play();
if(score < 100)
break;
level++;
}
if(level>4 && score>99)
isWinner = true;
else
isWinner = false;
return isWinner;
}
basic difference between while and do-while is do while will be executed at least once.
when do-while is best option?
in case when you want to execute some actions till you meet condition, of course you could achieve same thing by using while but early termination of loop with break, is nasty and ugly solution
When you want to execute the statement inside do for at least once, then you can go for it.
Directly from Docs
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once,
do {
statement(s)
} while (expression);
No, there is no time a do-while loops is the only option, it is used for convenience when you do not want to repeat code.
Related
I tried to do this LeetCode daily challenge but I've found out that my code loops infinitely.
I looked through it multiple times, but I cannot find where the problem is. If anyone could spot it, please answer.
public int longestValidParentheses(String s) {
int count, highestOne = 0, index = 0;
boolean isSevered = false;
boolean theEnd = false;
while(!theEnd) {
count = 0;
while(!isSevered) {
if(index<s.length()-2) {
if(s.charAt(index) == '(' & s.charAt(index++) == ')') {count = count + 2;index = index+2;}
else {isSevered = true;}}
else theEnd=true;isSevered=true;
}
highestOne = count;
}
return highestOne;
}
I have 2 suggestions for you:
Use indentation and do not write if/else on the same line as the code associated with them
Always, ALWAYS use bracelets, even if you have only a single command. I think one of the wrongs java did is letting the programmers the free not to use bracelets if there is just a single command after it. It confusing.
So you have 2 mistakes here that make your code run for infinity:
isSevered will always be true after one loop exactly, as you change it to true no matter what happens as it is outside the if else statements, hence the reason I wrote the 2 advices above.
You never changing isSeveres or theEnd at the outside loop. Meaning that if isSevers is true and theEnd is false, you will never enter the internal while and will never exit the outside while.
The two of those combined means that if the condition that make theEnd be initialized with true won't happen at the first run, you will be stuck with infinity loop.
So I have a loop that is wrapped around a loop and an if statement. When running the program however, it gets out of the inner loop (as planned) and then it fails the if statement (also as planned), resorting to the else statement which is a simple print.
What I /wanted/ to happen was have it then (in the case the if fails), restart to the original inner loop--hence the outer loop. But instead, after it fails the if statement, it begins to loop "phrase2" over and over.
Here is the simplified code:
int x = 1;
int y = 1;
int i = 0;
while(i == 0)
{
while(<condition that is false>)
{
System.out.println("phrase1");
a = input.nextInt();
b = input.nextInt();
}
if(<condition that is false>)
{
i = 1;
}
else
{
System.out.println("phrase2");
}
}
Thanks for your help regardless!
EDIT:
For the sake of emphasis...
What happens:
Infinite loop spewing "phrase2".
What I wanted:
After the else is executed, I wanted to be brought into the inner loop again.
Whatever condition you're using in the inner loop, just make sure it's true.
else
{
System.out.println("phrase2");
// SET THIS TO TRUE: <condition that is false>
}
This way, the inner loop will trigger again.
Your control never enters the below if statement
if(<condition that is false>)
{
i = 1;
}
You might need to adjust your conditions so that it comes into the above if block. Introduce a System.out.println inside if statement to debug
It looks like you have some code that you probably want to run once, unless something went wrong, and then you want to go back and retry. The idiom I usually use for that looks like
boolean needToRetry;
do {
needToRetry = false;
// do whatever
if (somethingWentWrong) {
needToRetry = true;
// set this at any point where you find you will need to go back
}
} while (needToRetry);
The important thing is that you need to reset your flag (needToRetry) at the beginning of the loop, each time. (P.S. There are other ways to do this using break or continue, although I personally don't like using continue.)
This is a highly subjective question, so I'll be more specific. Is there any time that a do-while loop would be a better style of coding than a normal while-loop?
e.g.
int count = 0;
do {
System.out.println("Welcome to Java");
count++;
} while (count < 10);`
It doesn't seem to make sense to me to check the while condition after evaluating the do-statement (aka forcing the do statement to run at least once).
For something simple like my above example, I would imagine that:
int count = 0;
while(count < 10) {
System.out.println("Welcome to Java"); count++;
}
would be generally considered to have been written in a better writing style.
Can anyone provide me a working example of when a do-while loop would be considered the only/best option? Do you have a do-while loop in your code? What role does it play and why did you opt for the do-while loop?
(I've got an inkling feeling that the do-while loop may be of use in coding games. Correct me, game developers, if I am wrong!)
If you want to read data from a network socket until a character sequence is found, you first need to read the data and then check the data for the escape sequence.
do
{
// read data
} while ( /* data is not escape sequence */ );
The while statement continually executes a block of statements while a particular condition is true
while (expression) {
statement(s)
}
do-while evaluates its expression at the bottom of the loop, and therefore, the statements within the do block are always executed at least once.
do {
statement(s)
} while (expression);
Now will talk about functional difference,
while-loops consist of a conditional branch instructions such as if_icmpge or if_icmplt and a goto statement. The conditional instruction branches the execution to the instruction immediately after the loop and therefore terminates the loop if the condition is not met. The final instruction in the loop is a goto that branches the byte code back to the beginning of the loop ensuring the byte code keeps looping until the conditional branch is met.
A Do-while-loops are also very similar to for-loops and while-loops except that they do not require the goto instruction as the conditional branch is the last instruction and is be used to loop back to the beginning
A do-while loop always runs the loop body at least once - it skips the initial condition check. Since it skips first check, one branch will be less and one less condition to be evaluated.
By using do-while you may gain performance if the expression/condition is complex, since it is ensured to loop atleast once. In that casedo-while could call for performance gain
Very Impressive findings here,
http://blog.jamesdbloom.com/JavaCodeToByteCode_PartOne.html#while_loop
The do-while loop is basically an inverted version of the while-loop.
It executes the loop statements unconditionally the first time.
It then evaluates the conditional expression specified before executing the statements again.
int sum = 0;
int i = 0;
do
{
sum += ids[i];
i++;
} while (i < 4);
Reference material
Simply, when you want to check condition before and then perform operation while is better option, and if you want to perform operation at least once and then check the condition do-while is better.
As per your question a working example,
1. when I needed to find the field which could be declared in the same class or the super class or the super class of that super class and so on i.e. finding the field located in deep class hierarchy. (A extends B B extends C and so on)
public Field SearchFieldInHierarchy(Object classObj, String fieldName )
{
Field type = null;
Class clz = classObj.getClass();
do
{
try
{
type = clz.getDeclaredField(fieldName);
break;
} catch (NoSuchFieldException e)
{
clz = clz.getSuperclass();
}
} while(clz != null || clz != Object.class);
return type;
}
2. When reading input stream from Http response
do
{
bytesRead = inputStream.read(buffer, totalBytesRead, buffer.length - totalBytesRead);
totalBytesRead += bytesRead;
} while (totalBytesRead < buffer.length && bytesRead != 0);
You kind of answer the question yourself-when it needs to run at least once, and it makes sense to read it that way.
do - while loop allows you to ensure that the piece of code is executed at least once before it goes into the iteration.
In a while loop, the condition is tested before it executes code in the loop. In a do while loop, the code is executed before the condition is tested, resulting in the code always being executed at least once. Example:
$value = 5;
while($value > 10){
echo "Value is greater than 10";
}
The above would never output anything. If we do the same again like this:
$value = 5;
do{
echo "Value is greater than 10";
}while($value > 10)
It would output Value is greater than 10 because the condition is tested after the loop is executed. After this it would not output anything further.
The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop instead of the top. Therefore, the statements within the do block are always executed at least once.
For example do check this link: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
If the looping condition can only be known after a first step of the loop (when you do not want a condition before you enter the loop).
Typically:
do {
expr = ...;
while (expr);
Use the while Statement when you have to check a condition repeatedly and only when the condition is satisfied execute the loop
while(condition) //eg. a>5
{
Body of Loop
}
If you see the flow of control here you can see that the condition is checked before the execution of the loop, if the condition is not met the loop will not execute at all
In the Do-While statement the program will execute the body of the loop once and then it will check if the statement is true or not
do
{
Body of Loop
}
while(condition); //eg. a>5
If you notice the flow of control here you will see that the body is executed once, then the condition is checked. If the condition is False the Program will break out of the loop, if True it will continue executing till the condition is not satisfied
It is to be noted that while and do-while give the same output only the flow of control is different
/*
while loop
5 bucks
1 chocolate = 1 bucks
while my money is greater than 1 bucks
select chocolate
pay 1 bucks to the shopkeeper
money = money - 1
end
come to home and cant go to while shop because my money = 0 bucks
*/
#include<stdio.h>
int main(){
int money = 5;
while( money >= 1){
printf("inside the shopk and selecting chocolate\n");
printf("after selecting chocolate paying 1 bucks\n");
money = money - 1 ;
printf("my remaining moeny = %d\n", money);
printf("\n\n");
}
printf("dont have money cant go inside the shop, money = %d", money);
return 0;
}
infinite money
while( codition ){ // condition will always true ....infinite loop
statement(s)
}
please visit this video for better understanding
https://www.youtube.com/watch?v=eqDv2wxDMJ8&t=25s
It is very simple to distinguish between the two. Let's take While loop first.
The syntax of while loop is as follows:
// expression value is available, and its value "matter".
// if true, while block will never be executed.
while(expression) {
// When inside while block, statements are executed, and
// expression is again evaluated to check the condition.
// If the condition is true, the while block is again iterated
// else it exists the while block.
}
Now, let's take the do-while loop.
The syntax of do-while is different:
// expression value is available but "doesn't matter" before this loop, & the
// control starts executing the while block.
do {
// statements are executed, and the
// statements is evaluated and to check the condition. If true
// the while block is iterated, else it exits.
} while(expression);
A sample program is given below to make this concept clear:
public class WhileAndDoWhile {
public static void main(String args[]) {
int i = 10;
System.out.println("While");
while (i >= 1) {
System.out.println(i);
i--;
}
// Here i is already 0, not >= 1.
System.out.println("do-while");
do {
System.out.println(i);
i--;
} while (i >= 1);
}
}
Compile and run this program, and the difference becomes apparent.
i have recrusive function which works fine. The problem is it gives stackoverflow error when the number of lines are huge. I want to put it in iterative, probably using a for loop. Need some help in doing it.
private TreeSet validate(int curLine, TreeSet errorSet) {
int increment = 0;
int nextLine = 0;
if (curLine == lines.length || errorSet.size() != 0) {
return errorSet;
} else {
String line = lines[curLine];
//validation starts. After validation, line is incremented as per the requirements
increment = 1 //As per requirement. Depends on validation results of the line
if (increment > 0) {
try{
Thread.currentThread().sleep(100);
}catch(Exception ex){
System.out.println(ex);
}
nextLine = (curLine + increment);
validate(nextLine, errorSet);
}
}
return errorSet;
}
Poster's description of the method:
The method does validates textlines, these lines has instructions of how much line has to be skipped, if the line is valid. So, if the line is valid that many of lines will be skipped using the increment. if the line is not valid increment will be 0.
I'm not sure why this was ever recursive in the first place. This is perfectly suited for the use of a FOR loop. use something like so:
private TreeSet validate(int curLine, TreeSet errorSet) {
int increment = 0;
if (errorSet.size() != 0)
return errorSet;
for (int curLine = 0; curLine < lines.Length; curLine += increment)
{
// put your processing logic in here
// set the proper increment here.
}
}
If the increment is always going to be 1, then you can just use curr++ instead of curLine += increment
for(String line : lines) {
// validate line here
if(!errorSet.isEmpty()) {
break;
}
}
The solution for your problem could be simple for loop or while, with logical expression for stop condition. Typically we use for loop when we have to pass through all elements of Iterable or array. In case when we are not aware how many loops we are going to do we use a while loop. Advantage of for loop over while, is that we for free have localized variables so we ca not use them out side of the loop, therefore we reduce possibility to have some bug.
You problem is that you have to break the program on two conditions:
When errorSet is not empty.
When the array of lines have no longer items.
As contradiction, we can say that your program should continue:
Until errorSet is empty,
and until line number is smaller than array size where they are stored.
This provide us to simply expression
errorSet.isEmpty()
lineNumber < lines.length()
We can combine them using logical operator && and use as a stop rule in for loop.
for(int lineNumber= 0; errorSet.isEmpty() && lineNumber< lines.length(); lineNumber++) {
//code to operate
}
Note:
Typically for logical expression is used operator &&, that assure that every part of the logical expression is evaluated. An alternative for this is &, that in case of false do not operate longer and return false. We could be tempted to use this operator for this expression but i would be bad idea. Because when we would traversed all lines without error code will generate IndexOutOfBoundException, if we switch the places then we would not have any optimization as first expression would be evaluated same number of times.
I saw this keyword for the first time and I was wondering if someone could explain to me what it does.
What is the continue keyword?
How does it work?
When is it used?
continue is kind of like goto. Are you familiar with break? It's easier to think about them in contrast:
break terminates the loop (jumps to the code below it).
continue terminates the rest of the processing of the code within the loop for the current iteration, but continues the loop.
A continue statement without a label will re-execute from the condition the innermost while or do loop, and from the update expression of the innermost for loop. It is often used to early-terminate a loop's processing and thereby avoid deeply-nested if statements. In the following example continue will get the next line, without processing the following statement in the loop.
while (getNext(line)) {
if (line.isEmpty() || line.isComment())
continue;
// More code here
}
With a label, continue will re-execute from the loop with the corresponding label, rather than the innermost loop. This can be used to escape deeply-nested loops, or simply for clarity.
Sometimes continue is also used as a placeholder in order to make an empty loop body more clear.
for (count = 0; foo.moreData(); count++)
continue;
The same statement without a label also exists in C and C++. The equivalent in Perl is next.
This type of control flow is not recommended, but if you so choose you can also use continue to simulate a limited form of goto. In the following example the continue will re-execute the empty for (;;) loop.
aLoopName: for (;;) {
// ...
while (someCondition)
// ...
if (otherCondition)
continue aLoopName;
Let's see an example:
int sum = 0;
for(int i = 1; i <= 100 ; i++){
if(i % 2 == 0)
continue;
sum += i;
}
This would get the sum of only odd numbers from 1 to 100.
If you think of the body of a loop as a subroutine, continue is sort of like return. The same keyword exists in C, and serves the same purpose. Here's a contrived example:
for(int i=0; i < 10; ++i) {
if (i % 2 == 0) {
continue;
}
System.out.println(i);
}
This will print out only the odd numbers.
Generally, I see continue (and break) as a warning that the code might use some refactoring, especially if the while or for loop declaration isn't immediately in sight. The same is true for return in the middle of a method, but for a slightly different reason.
As others have already said, continue moves along to the next iteration of the loop, while break moves out of the enclosing loop.
These can be maintenance timebombs because there is no immediate link between the continue/break and the loop it is continuing/breaking other than context; add an inner loop or move the "guts" of the loop into a separate method and you have a hidden effect of the continue/break failing.
IMHO, it's best to use them as a measure of last resort, and then to make sure their use is grouped together tightly at the start or end of the loop so that the next developer can see the "bounds" of the loop in one screen.
continue, break, and return (other than the One True Return at the end of your method) all fall into the general category of "hidden GOTOs". They place loop and function control in unexpected places, which then eventually causes bugs.
"continue" in Java means go to end of the current loop,
means: if the compiler sees continue in a loop it will go to the next iteration
Example: This is a code to print the odd numbers from 1 to 10
the compiler will ignore the print code whenever it sees continue moving into the next iteration
for (int i = 0; i < 10; i++) {
if (i%2 == 0) continue;
System.out.println(i+"");
}
As already mentioned continue will skip processing the code below it and until the end of the loop. Then, you are moved to the loop's condition and run the next iteration if this condition still holds (or if there is a flag, to the denoted loop's condition).
It must be highlighted that in the case of do - while you are moved to the condition at the bottom after a continue, not at the beginning of the loop.
This is why a lot of people fail to correctly answer what the following code will generate.
Random r = new Random();
Set<Integer> aSet= new HashSet<Integer>();
int anInt;
do {
anInt = r.nextInt(10);
if (anInt % 2 == 0)
continue;
System.out.println(anInt);
} while (aSet.add(anInt));
System.out.println(aSet);
*If your answer is that aSet will contain odd numbers only 100%... you are wrong!
Continue is a keyword in Java & it is used to skip the current iteration.
Suppose you want to print all odd numbers from 1 to 100
public class Main {
public static void main(String args[]) {
//Program to print all odd numbers from 1 to 100
for(int i=1 ; i<=100 ; i++) {
if(i % 2 == 0) {
continue;
}
System.out.println(i);
}
}
}
continue statement in the above program simply skips the iteration when i is even and prints the value of i when it is odd.
Continue statement simply takes you out of the loop without executing the remaining statements inside the loop and triggers the next iteration.
Consider an If Else condition. A continue statement executes what is there in a condition and gets out of the condition i.e. jumps to next iteration or condition. But a Break leaves the loop.
Consider the following Program. '
public class ContinueBreak {
public static void main(String[] args) {
String[] table={"aa","bb","cc","dd"};
for(String ss:table){
if("bb".equals(ss)){
continue;
}
System.out.println(ss);
if("cc".equals(ss)){
break;
}
}
System.out.println("Out of the loop.");
}
}
It will print: aa cc Out of the loop.
If you use break in place of continue(After if.), it will just print aa and out of the loop.
If the condition "bb" equals ss is satisfied:
For Continue: It goes to next iteration i.e. "cc".equals(ss).
For Break: It comes out of the loop and prints "Out of the loop. "
The continue statement is used in loop control structure when you need to jump to the next iteration of the loop immediately.
It can be used with for loop or while loop.
The Java continue statement is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition.
In case of an inner loop, it continues the inner loop only.
We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop.
for example
class Example{
public static void main(String args[]){
System.out.println("Start");
for(int i=0; i<10; i++){
if(i==5){continue;}
System.out.println("i : "+i);
}
System.out.println("End.");
}
}
output:
Start
i : 0
i : 1
i : 2
i : 3
i : 4
i : 6
i : 7
i : 8
i : 9
End.
[number 5 is skip]
I'm a bit late to the party, but...
It's worth mentioning that continue is useful for empty loops where all of the work is done in the conditional expression controlling the loop. For example:
while ((buffer[i++] = readChar()) >= 0)
continue;
In this case, all of the work of reading a character and appending it to buffer is done in the expression controlling the while loop. The continue statement serves as a visual indicator that the loop does not need a body.
It's a little more obvious than the equivalent:
while (...)
{ }
and definitely better (and safer) coding style than using an empty statement like:
while (...)
;
continue must be inside a loop Otherwise it showsThe error below:
Continue outside the loop