I have a counter which counts to 4 in a loop, and a counter which counts how many of these loops have passed.
In my code below both labels setVisibility to true at count 1.
But I want label1 to appear at count 1 and label2 at count 2.
My question to you is:
What’s more efficient, to set the labels visibility with only if statements, or
can I use do-while statements multiple times?
class counters2 implements ActionListener
{
int count = 0, alternativecounter = 0;
public void actionPerformed(ActionEvent e)
{
int fakeSecond = (count++ % 4) + 1;
if(fakeSecond == 1)
{
alternativecounter += 1;
if(alternativecounter == 3)
{
do
{
label1.setVisible(true);
}while(count == 1);
do
{
label2.setVisible(true);
}while(count == 2);
}
}
}
}
A
do whileis meant for loops – that is, repeatedly executing code. Did you notice that, ifalternativecounteris3, the code enters an infinite loop? Further, the body of ado whileis always executed at least once, so (infinite loop aside) this code is not correct.If the code to loop you’re trying to conditionally execute shouldn’t be executed more than once (and here, it’s clear that it really shouldn’t), use an
ifstatement.As others have said, this is also a ridiculous way to try to optimize your code – it’s premature optimization and micro-optimization at that.