Is it ok to do this to simplify a do-while loop? or should for only be used for incrementing/decrementing?
String res;
for(res=null;res==null;res=op.getOrderID());
instead of:
String res = null;
do {
res = op.getRetOrderID()
} while (res == null);
I think it's better to stick with the do-while loop. This is the standard idiom for the situation when you want the body of the loop to be executed at least once.
One good reason for sometimes using a for loop in preference to a while or do-while loop is that you can make the variable checked in the termination condition local to the loop. You definitely don't want that here as you need it afterwards.
Simple Advice :
use for loop when you know the number of repetitions .
use while loop when you do not know the number of repetitions .
use do-while loop when you want to run your code one time at least and do not know the number of repetitions .
Good Luck .
Related
What does this condition mean in Java?
while(n>0)
I'm a newbie at Java and I've never seen this kind of code in conditions.
just do a search on while loop.
here is a link to wiki
while(n>10)
{
// do stuff..
}
.. simply means execute that block of code as long as n > 10.. normally you would have something inside that code block to make n greater than 10 at some point.. otherwise you would have an infinite loop.. which is bad..
It means that as long as the variable named "n" evaluates to a value greater than 0, what ever logic is inside the while loop code block will continue to execute. FYI - a quick Google search will reveal thorough information and examples on while loops.
the expression inside of a while loop is always a boolean expression;
here you are expressing that a variable, n, is greater than 0.
if true, you enter the loop,
else, you do not.
For a situation like this, it is likely that n is an integer
https://www.tutorialspoint.com/java/java_while_loop.htm
This question already has answers here:
Why use a "do while" loop? [closed]
(9 answers)
Closed 1 year ago.
I know what do does, and how it cooperates with the while loop, but won't a while loop code be the same, whether or not the do is there?
Consider the following:
while(condition){
myFunction();
}
and
do{
myFunction();
}while(condition);
The second form executes myFunction() at least once then checks the condition! To do so with a while loop you've to write:
myFunction();
while(condition){
myFunction();
}
The biggest difference between while and do-while statement is, whether it is executed at least one time or not.
while(false)
printf("print!");
with this statement, the program will never print the string. However,
do{
printf("print!");
}while(false);
with this statement, the program will print the string once.
But many people don't recommend to use do-while statement--because it can be substituted with while statement. It doesn't mean that do-while statement is critically harmful, but it is rarely used.
In fact, for loop is the most safe and recommended way because the programmer can handle the iteration number, loop conditions, and increasing variables easily. So if you don't have any specific reason that you have to use while loop, just use for loop.
Use do-while() construct when you have to get your task executed at least once even if condition fails.
Use while() when you your task to be executed only on certain condition success.
The difference is with "do-while" loop will be executed at least one time. With "while" loop with false condition the loop body will not be executed.
if you write the "loop" like so (without the do as in your question):
int i=0;
{
System.out.println(i++);
}while(i<10);
it will just print out 0 (nothing more), and not loop 10 times.. so no, the loop won't be the same if the do isnt there.
This question already has answers here:
How does a for loop work, specifically for(;;)?
(6 answers)
Closed 9 years ago.
What is the meaning of for (;;)?
I found it in a certain base class and I cannot find explanation for in on the net.
Please also explain when and how to use this expression
It's an infinite loop. It has no initial condition, no increment and no end condition.
It's the same as
while(true) {
//do stuff
}
You can use it when you need something to be repeated continuously, until the application ends. But i would use the while version instead
It is read "for ever". the default for the condition is to evaluate to true.
When should you use it? If you don't want the loop to end (as is common in servers) or when the end condition is naturally known only in the middle of the loop, in which case you can use break:
for (;;) {
String in = get_input();
if (in.equals("end"))
break;
System.out.println("you entered " + in);
}
This is not the best example, though. You can do without the infinite loop here. For example:
for (String in = get_input(); !in.equals("end"); in = get_input()) {
System.out.println("you entered " + in);
}
It means an infinite loop. It is not considered a good practice to use this. Instead try while(true)
In some cases where you want to do a task again and again, sometimes forever. Such cases you use an infinite loop. This can be done in many ways. Notable ones are,
Using while,
while(true)
{
// Task you want to repeat
}
Using for,
for(;;)
{
// Task you want to repeat
}
Note : You might have to be very much careful while implementing infinite loops as there exists a possibility of same problem recurring. It is a good practice to catch the exception and retry for some time and if still problem persist, break from the loop.
The following is part of the code for my college assignment.
else if (!codeList.contains(userCode)) {
i--; // i is the counter for the for-loop
}
else if (userQuantity[i]==0) {
i--;
}
The first part makes sure that if the user enters the wrong code, the counter i does not increment 1, or rather, it subtracts 1 from the recently incremented counter. This part works fine.
The second part however is what I seem to be having problems with. userQuantity[] is an int array and it has to be an array. This does not seem to do anything to the code. Even if 0 is entered for the quantity, it still incrememnts the counter which is not desireable.
I should explain, to avoid confusion, that this is an infinite for-loop (with a break statement). The reason I am doing a for-loop is because I am required to. Is it because of my for-loop that the condition isn't working or am I doing something completely wrong with it?
This is for my college assignment so I would appreciate answers with explanation and not just quick-fixes. If you need me to explain, let me know please.
Although it's not strictly illegal in Java, it's not a good idea to change the value of the for loop control variable from within the loop. (Such modification is illegal in some other languages.)
By changing the loop iteration variable within the loop, you're messing with the implicit assumptions offered by your use of a for loop. For example, if a reader sees:
for (int i = 0; i < 10; i++) {
// ...
}
the reader will rightfully assume that the loop is intended to execute exactly 10 times (or, no more than 10 if there is a break in there). However, if you go changing the value of i within the loop, this assumption is no longer valid.
If you must change the value of the counter, I would suggest writing this as a while loop instead:
int i = 0;
while (i < 10) {
// ...
i++;
}
along with a comment that explains why you are changing i within the loop and what it means to do so.
This is very bad practice. Change the for loop to a while loop and only increment if
codeList.contains(userCode)==true or userQuantity[i]!=0.
I should explain, to avoid confusion, that this is an infinite for-loop (with a break statement). The reason I am doing a for-loop is because I am required to. Is it because of my for-loop that the condition isn't working or am I doing something completely wrong with it?
I have a feeling that you are misunderstanding the requirements (e.g. you are not required to use a for loop), or that there is a mistake in your thinking; i.e. there is a simpler solution that doesn't involve the counter going backwards.
(It is surprising that a programming exercise would require you to write code that most experienced Java programmers would agree is bad code. The simple explanation is that it is not.)
Either way:
Changing the loop variable in a for loop is bad practice, for the reasons described by Greg.
The idea of an "infinite for loop" is really strange. The following is legal Java ...
for (int i = 0; true; i++) {
...
}
but the idiomatic way to write it is:
int i = 0;
while (true) {
...
i++; // ... at the appropriate point / points
}
... which in most cases means that you don't need to make the variable go backwards at all.
I have a code something like this
Enumeration parameterEnum = request.getParameterNames()
while(parameterEnum.hasMoreElements()){}
what is the difference if I change it from a while statement into an if statement?
If you change it to an if it will either execute once or not at all - a while statement will execute indefinitely until ParameterEnum.hasMoreElements() returns false.
If I understand what you are asking, the current code would keep running whatever is in the brackets until there are not elements. This assumes that what is in the brackets takes off elements. As literally shown above, it is an infinite loop and will never end.
If you convert the while to an if, then what is in the brackets will run only once.
If Request.getParameterNames() returns an "empty" whatever-it-is, then neither case will do anything.
The if will be much, much faster!!! its complexity is O(1) and that of while's is O(N)!!!
So, the larger the input is, the better it is to use an if instead of a while ;-)
You might be thinking of a for statement, not an if.
if(ParameterEnum.hasMoreElements()) {}
The if will only run once
while(ParameterEnum.hasMoreElements()) {}
the while will run continuously, unless you increment the enum.
the other option is for:
for(Enumeration paramEnum = Request.getParameterNames();
parameEnum.hasMoreElements();) {}
this is similar to the while, and will run for as long as the hasMoreElements() method returns true, so incrementing the enum with nextElement() is important.