I was about to post a query but I solved it by reworking the code avoiding the issue but not answering it.
So below is an example of what I was wanting to do.
I had a for loop inside a do-while loop and wanted the do-while loop to run until a condition relating to the nested for loop was reached. The error I was getting was that i wasn't initialised so the while condition could not be run, which makes sense.
I was hoping to create a local variable outside the do-while loop and initialize it in the nested for loop. This obviously wasn't possible in the way I was trying to execute it but is there another way to 'post initialise' a variable in Java?
Also just out of curiosity what languages allow such post initialisation?
case 2:
int i;
do{
try{
for(i=0; i<array.length;i++){
if(...
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
} while(!array[i].state.equals("X"));
break;
You can easily solve it by giving i an initial value when you declare it :
int i = 0;
You have to initialize de variable i before the do-while.
Inside the do-while loop you can reset the variable. Now you've already made it in the for condition.
On the other hand, I don't know what your code inside for made it and the logic of your algorithm, but I think that it's possible you have a infinite loop if there aren't any element with the state "X". I think that it is very posible indeed (of course depends of your algorithm) to remove the for loop and add the code in the do-while with a i++ and an end condition like this: while(!array[i].state.equals("X") && i < array.lengh);
Related
When it comes to counting, should a do-while loop be used, or a for loop? Because this:
class Main {
public static void main(String[] args) {
int times = 1;
do {
System.out.println("I have printed " + times + " times.");
times++;
} while (times < 6);
}
}
Seems to do the exact same thing as this:
class Main {
public static void main(String[] args) {
for (int times = 1; times < 6; times++) {
System.out.println("I have printed " + times + " times.");
}
}
}
Is it a difference in speed? Preference? Situation? Personal quirks? Some kind of "Java social taboo"? I have no idea. Either seem to be able to be used for effective counting, just that one takes a lot more. And both print the exact same thing.
System.out.println("Many thanks!!");
You're right, these do the same thing (except one starts counting at 0 and the other at 1, but that's just an implementation detail). If your program knows in advance (before the loop starts) how many times you want the loop to iterate, most Java developers will tell you to go with a for loop. That's what it's designed for.
A while loop or do while loop is better suited for situations where you're looking for a specific value or condition before you exit the loop. (Something like count >= 10 or userInput.equals("N"). Anything that evaluates to a boolean True/False value.)
When faced with these kind of dilemmas, aim for readability and familiarity. You should not concern yourself with micro-optimizations. Focus on readability and clearly conveying you intent. Do as other do in similar situation.
Like #Bill-The-Lizard said, while loop suggests to the reader of your code that you opted for it, because you're not counting, but repeating until a condition is met. At least once - otherwise you'd have chosen while(...){ } loop.
In other words, for, do {} while() and while() { } generally work the same. But one may better convey you intent in your particular piece of logic.
I think it's more of a readability and syntactic sugar. This while condition
while (condition)
can also be written as
for (; condition; )
but obviously the first one looks lot better and is more readable.
It depends on the programmer's choice when to use for loop or do while loop but the general practice followed by most of the programmers is
For loop
When you know that the loop will execute a predefined number of times(general practice since you can also use for(;true;) which loops forever).
For example a loop which runs 10 times or n number of times where n is a variable
for(int i = 0; i < n; i++) {
//Do something
}
While loop
When you know that the loop should terminate after the evaluation of a specific condition as true or else you want the loop to run forever (like while(true)) and check the break conditions inside the while loop.
Also the while loop is preferred when you can't figure out the conditions in the first place and start with while(true) but once you write code inside the loop you get good understanding of what's happening and get the idea about which conditions to check thus when to exit the loop.
For example
while(x != 0) {
//Do something;
x--;
}
while(true) {
// some code to execute on which the condition depends
if(condition is true) {
break;
}
}
Do while loop
Do while loop is similar to the while loop but with a small difference. That is it allows the first iteration to happen without checking the condition(specified in the while statement, but you can still evaluate the condition inside the block(curly braces)).
By convention most Java developers use for loops. Effective Java recommends for loops instead of while loops because the loop variable can use a tighter scope which reduces bugs. http://www.corejavaguru.com/effective-java/items/45
Recent versions of Java also allow the following
IntStream.range(0, 6).forEach(
i -> System.out.println("I have printed " + i + " times.")
);
Beyond personal preferences, this one has the advantage that the index is maintained by the runtime and there is no need for the programmer to ++i
I was writing a code to insert an element at the end of the linked list. However without using the semi-colon at the end of for, I'm unable to get the list updated properly, what is the significance of this semi-colon and how is this affecting my code?
public void insertAtEnd() throws IOException {
LinkedList node=new LinkedList();
System.out.println("Enter an element");
int value=Integer.parseInt(br.readLine());
node.setData(value);
LinkedList p,q;
for(p=head; (q=p.getNext())!=null; p=q);
p.setNext(node);
}
The semicolon means that the statement below won't be executed until the loop has exited. Your case, the loop is taking p to the end of the list (the last element) and then the next statement is assigning its next value to the new element
Well, the way it is constructed right now as for(p=head; (q=p.getNext())!=null; p=q);, the for loop has an empty body. The variables p and q through the p.getNext() and p=q assignments are updating. Then it is executing the p.setNext(node); a single time.
EDIT: As to why the code is working with the semi-colon, it is because you are advancing the variables p and q over the list. While the for loop with the empty body is fine, I think traditionally one sees a while loop.
The indentation of the p.setNode(node); makes it appear as if the statement were related to the for loop, but it really isn't, as the goal is to find the end of the linked list by iterating over it.
(note: others made similar points while I was typing this answer)
it needs to be removed, it is causing it to do nothing in the loop.
The loop will execute the next single block of code after the loop. Either one statement, or one { } code block.
In this case, you have one statement ;, so it "executes" and does nothing, and then will call your p.setNext(node); after the loop ends.
public void insertAtEnd() throws IOException {
LinkedList node=new LinkedList();
System.out.println("Enter an element");
int value=Integer.parseInt(br.readLine());
node.setData(value);
LinkedList p,q;
for(p=head; (q=p.getNext())!=null; p=q)
p.setNext(node);
}
The semicolon is essentially transforming what you appear to want to do because of your indentation:
for(p=head; (q=p.getNext())!=null; p=q)
{
p.setNext(node);
}
into the following:
for(p=head; (q=p.getNext())!=null; p=q)
{
}
p.setNext(node);
So with the semicolon your loop is executing nothing at every iteration. Then, after it has finished executing, you're running p.setNext(node); exactly once.
Usually you can avoid this problem in the future by explicitly writing your curly braces as I have done in these two code segments. It is unclear exactly which code segment you are trying to accomplish right now.
The for statement provides a compact way to iterate over a range of values. Programmers often refer to it as the "for loop" because of the way in which it repeatedly loops until a particular condition is satisfied. The general form of the for statement can be expressed as follows:
for (initialization; termination; increment) {
//statement(s)
}
When using this version of the for statement, keep in mind that:
The initialization expression initializes the loop; it's executed once,
as the loop begin
When the termination expression evaluates to false, the loop terminates.
The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
In your case, the loop is taking p to the end of the list (the last element) and then the next statement is assigning its next value to the new element
I've started to learn java, and in some examples I've seen special for loop (not very familiar to me). It's not enhanced for loop, but it looks like this
for(;;i++){ do something..}
I don't know what it means, when I just have these semicolons o.O If someone could explain it to me, would be grateful.
I would read through this: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
As you might notice,
The general form of the for statement can be expressed as follows:
for (initialization; termination;
increment) {
statement(s)
}
...
The three expressions of the for loop are optional; an infinite loop can be created as follows:
// infinite loop
for ( ; ; ) {
// your code goes here
}
(emphasis mine)
In your example, I would expect the variable i would have been declared and initialized before the for loop. If there is no termination condition, the loop will run infinitely.
You can also have a termination condition inside a loop, something like :
if(i = some number) {break;} //this will break the loop
Similarly, the increment statement can also be declared inside a loop.
This question already has answers here:
Is it a bad practice to use break in a for loop? [closed]
(19 answers)
Closed 7 years ago.
I am just curious as I have been using break statements a lot, but apparently I was told that is bad practice. Obviously logically if something is met it could terminate as well. I just want to know if there is something else besides break.
That would break out of the for loop. In fact break only makes sense when talking about loops, since they break from the loop entirely, while continue only goes to the next iteration
try this:
for(int i= 0; i<MAX; i++){
if(listEmpt[i] == null){
listEmpt[i] = employeeObj;
i=MAX;
}
but I see no problem with using breaks. There will always be circumstances where you want to stop processing a loop, and using a break; makes much more sense (and makes it more readable!) than setting your loop counter up to a value that would make your loop stop at the next iteration.
you can also use labeled breaks that can break out of outer loops (and arbitrary code blocks)
looplbl: for(int i=;i<;i++){
if (i == temp)
// do something
else {
temp = i;
break looplbl;
}
}
An unlabelled break only breaks out of the enclosing switch, for, while or do-while construct. It does not take if statements into account.
See for more details.
With regards about the use of break, you could check here.
Since while loops were not covered (another form of looping which I personally use a lot), you could look towards settings conditions for the loops such as
boolean flag = true;
while (flag) {
//do something that modifies the below condition
if (condition) {
//do something
flag = false;
}
}
Upon which the loop will terminate when the condition equates to true, since that sets the flag to false.
If you simply return from within your loop, that should be sufficient. Most people think you have to terminate the loop, but this is not the case.
Also, see this answer too.
I'm reading a Java book and I came across an interesting for loop. It looks like this:
for(; (j>0) && (tmp < a[j-1]); j--)
I understand that (j>0) && (tmp < a[j-1]) is the condition check and j-- is the decrease of the variable. However, I don't get where's the initialization statement.
There is no initialization statement in your example. It's optional.
j is probably declared and initialized before the loop.
Normally, you would initialize j in the first statement in the for loop (which is empty here) since it is a looping index and is usually only used inside the loop. Also the standard syntax for Java for loops is for( initialization; termination condition; increment), but the language only enforces that there be three statements (with the middle one being a boolean expression) , so you can have three empty statements for(;;) which creates an infinite loop or you could put some other statement in there (except for the middle expression where a boolean expression is expected) like for(System.out.println("I was supposed to initialize here"); false && true; logger.log("Nope.")). OF course, you shouldn't do that, but it is legal.
Note: Some statements would be illegal if put in place of the third statement as well, like variable declarations, since it is executed at the end of each iteration (see this for more on legal for loop syntax)
I like to think of for loops as a shorthand for a common form of the while loop, where you want to loop a number of times:
int i= 0; // Initialization
while (i< max){ // termination
// Do stuff
i++; // increment
}
which is helpful for understanding what it does with these statements.
for(initialization; condition; increment)
None of them are a must to declare a for loop. You can have a for loop like for(;;) if you want. It will compile without any errors.
According to your question j have been already initialized some where. Therefore it is perfectly fine.