Java/Eclipse - Conditional breakpoint and counter? [duplicate] - java

This question already has answers here:
How to use conditional breakpoint in Eclipse?
(6 answers)
Closed 5 years ago.
Is it possible to have a condition on a breakpoint in Eclipse, and have the breakpoint "activate" after that condition has been met n times?
Say for example, in some sloppy mobile-written pseduocode, the breakpoint's condition is:
int n = 0;
If(i == j){
n++
If(n > 400)
true;
}
With i and j being values in my class.
To please the duplicate-hunt, note that I am not asking how to use a conditional statement, I am asking how I can count the number of times a breakpoint condition is met, then have the breakpoint stop my code. Hit does not do this, nor does using a condition in any way I can figure out.

To activate the breakpoint after the condition is met a certain number of times:
Open breakpoints dialog: Ctrl+double-click breakpoint
Check Conditional checkbox
Use following as condition:
if (i == j) {
int n = Integer.parseInt(System.getProperty("breakpoint.n", "0"));
n++;
System.setProperty("breakpoint.n", "" + n);
if (n > 400) return true;
}
return false;

Related

What does this mark before for loop do? [duplicate]

This question already has answers here:
"loop:" in Java code. What is this, and why does it compile?
(12 answers)
Closed 4 years ago.
I was reading ThreadPoolExecutor's source code and saw the following code.
private boolean addWorker(Runnable firstTask, boolean core) {
retry:
for (;;) {
int c = ctl.get();
int rs = runStateOf(c);
// Check if queue empty only if necessary.
if (rs >= SHUTDOWN &&
! (rs == SHUTDOWN &&
firstTask == null &&
! workQueue.isEmpty()))
return false;
for (;;) {
int wc = workerCountOf(c);
if (wc >= CAPACITY ||
wc >= (core ? corePoolSize : maximumPoolSize))
return false;
if (compareAndIncrementWorkerCount(c))
break retry;
c = ctl.get(); // Re-read ctl
if (runStateOf(c) != rs)
continue retry;
// else CAS failed due to workerCount change; retry inner loop
}
}
Notice the retry word above. What does it do? I've never seen similar usages before. Is there a documentation about this syntax?
retry is not a keyword, but an identifier. It's a label. See the Java Language Specification for the break statement.
A break statement with label Identifier attempts to transfer control to the enclosing labeled statement (ยง14.7) that has the same Identifier as its label; this statement, which is called the break target, then immediately completes normally. In this case, the break target need not be a switch, while, do, or for statement.
Instead of breaking out of the innermost enclosing loop as it does by default, adding the identifier causes control to transer to the part of the code identified by this label.
In this case, when execution arrives at the break retry statement, it will go to a label retry: and continue from there.

Can I return Boolean value in a loop statement? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I just came up with a problem returning a Boolean value in accordance with a given condition. I thought in order to check the given condition for full possibilities I need to use for loop. But when I tried to compile it, it gives me error, possibly because there is uncertainty returning a Boolean value using for loop. Here is an original problem:
Return true if the given string contains a "bob" string, but where the middle 'o' char can be any char.
bobThere("abcbob") โ†’ true
bobThere("b9b") โ†’ true
bobThere("bac") โ†’ false
And here is my code:
public boolean bobThere(String str)
{
for(int i=0; i<str.length()-3; i++)
{
if (str.length()>=4): && str.charAt(i)=='b' && str.charAt(i+2)=='b')
{
return true;
}
else
return false;
else if (str.length()==4 && str.charAt(0)=='b' && str.charAt(2)=='b')
{
return true;
}
else
{
return false;
}
}
}
I just wanted to ask :
1. Can I fix the this code for returning a value. I mean, can I use for loop and return specific value for a given condition? If yes, please could you give me a sample.
2. Or are there any ways other than for loop to solve this problem.
Thanks in advance.
The compiler error is almost certainly because you have an elseif after an else. That's invalid.
Looking at your code, what you seem to want to do is loop through the string, and then return true if you're at the start of a b?b string. I'm not sure why you have your second if condition in there - at the moment your code would check the first and third characters of the string on every iteration of the loop, if the string happens to be exactly four characters long. Pointless, it doesn't need to be there. The check for length isn't necessary at all.
Additionally, your end condition for the loop is currently i < string.length()-3. This means that the final three characters of the string will not be checked. You would need to change this to either i <= string.length()-3 or i < string.length()-2 to solve this.
Your else return false stuff is going to give you a serious problem. Your code will enter the loop once, and then either return true or false, without ever going to the next phase of the loop. What you should do is loop through the string, and if you find what you're looking for, return true. Otherwise, don't return at all, and keep going with the loop. If you get to the end of the loop it means you never found what you were looking for, so you can at that point return false.
Taking those comments into account, your revised code would look like this (please note I haven't compiled or run this):
public boolean bobThere(String str)
{
for(int i = 0; i <= str.length() - 3; i++)
{
if (str.charAt(i) == 'b' && str.charAt(i + 2) == 'b')
{
return true;
}
}
return false;
}

while loop does not preform else statement and repeat loop

When compiled upon not entering the right selection it doesnt display to re-enter or repeat the loop
int counterA = 0;
while (counterA < 0) {
if (conversionSelection.equalsIgnoreCase("binary"))
counterA++;
if (conversionSelection.equalsIgnoreCase("octal"))
counterA++;
else System.out.println("Error. Please enter weither to convert the Hex to Octal or Binary:");
conversionSelection = keyboard.nextLine();
}
The loop should not execute at all since the condition fails right from the get-go.
There is also a dangling else statement. So you need to have an else-if for your second if statement if you want the else to properly execute. While it may not currently produce errors, it is an important skill to prevent dangling 'else's'.
Your code will never enter the while loop since counterA = 0 and the while loop condition is for it to be < 0. You want counterA to be less than zero, or the condition to include counterA's value in its set (e.g. while (counterA <= 0)).
This loop will never start because 0 is not smaller than 0.

In Java, when is a "do while" loop the only option?

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.

What does for (;;) mean in Java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does for (;;) mean in Java?
I am reading some Java API docs, and I have encountered this loop of a very strange perky look, which elated me to come here and ask what is it about. Would be glad to find it as soon as possible. Thank you on your upcoming efforts.
public int read() throws IOException {
synchronized (lock) {
ensureOpen();
**for (;;)** {
if (nextChar >= nChars) {
fill();
if (nextChar >= nChars)
return -1;
}
if (skipLF) {
skipLF = false;
if (cb[nextChar] == '\n') {
nextChar++;
continue;
}
}
return cb[nextChar++];
}
}
}
for(;;)
That is an infinite loop.
For example, it's equivalent to something like
while(true)
Naturally, to exit such a loop, a branching statement is used.
EDIT: clearly the use of the word "infinite" was a bad choice. Still, for all intents and purposes, a for(;;) loop does not terminate using the same conditional mechanism of typical for loops. I believe this was the point of the question. The comments are just splitting hairs at this point.
for(;;)
This is an infinte loop, no variables initialization, no condition to check, no incremental step ... only exits the loop when execute the "return" sentence inside conditions.
Common for loop:
for(int i = 0 ; i < max ; i++)
Hope helps.
It means that the condition of termination of the cycle is not expressed in the usual form.
The only ways to terminate the cycle are the two return statements.
As stated by #Tom, this is an infinite loop.
Uses of this in your program could be if you would like to execute something forever.

Categories

Resources