Is there any value that could be assigned to the myString
variable that would result in an infinite loop in the code below?
while (true) {
if (myString.indexOf(" ") == -1) {
break;
}
myString = myString.replaceAll(" ", " ");
}
In each iteration you calculate a number (the sum of the squares of the digits or the previous number). You can put all those numbers in a Set. If in some iteration you calculate a number that is already in that Set, you know that you are stuck in an infinite loop.
Basically, the infinite loop happens when the condition in the while loop always evaluates to true. This can happen when the variables within the loop aren't updated correctly, or aren't updated at all.
What is an Infinite Loop? An infinite loop occurs when a condition always evaluates to true. Usually, this is an error. For example, you might have a loop that decrements until it reaches 0.
You can run a for loop infinitely by writing it without any exit condition.
Could this code potentially result in an infinite loop?
No. But if might throw an exception if myString
is null
.
If the String doesn't contain two spaces, it'll break;
after the first iteration. Otherwise, it does contain two spaces, and it replaces it with one space, then, it won't have two spaces again, and it'll break;
.
No, it won't - however the loop could be much better structured:
while (myString.indexOf(" ") != -1) {
myString = myString.replaceAll(" ", " ");
}
Sometimes you need break in a loop, but if you don't need it you should avoid it.
A better solution of course would be to not use a loop at all, remember that replaceAll works from regex:
myString = myString.replaceAll("[ ]+", " ");
For example:
String str = "this is a test string with long white space chunks";
System.out.println(str.replaceAll("[ ]+", " "));
Try it here: http://www.tryjava8.com/app/snippets/52c19090e4b00bdc99e8a943
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With