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);
}
}
}
}
开发者_如何学Go
A do while
is meant for loops - that is, repeatedly executing code. Did you notice that, if alternativecounter
is 3
, the code enters an infinite loop? Further, the body of a do while
is 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 if
statement.
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.
Your code as written will either not execute the do/while, or result in an infinite loop if it does. Don't worry about efficiency, and work on making this code readable and correct.
An event listener should only handle a single event. So at the time of the event you check the state of your variable and then do the related processing.
So you would never use a do/while. In fact in your posted code you have introduced an infinite loop. This infinite loop will in turn freeze the GUI because it won't be able to respond to other events.
精彩评论