Reputation: 1007
I need to read some big text file in scala. And append a line in that file to StringBuilder
. But I need to break the loop if the line in that file contain some String. And I don't want to append that String to StringBuilder. For example in java, loop A
will include "pengkor"
in resulted string. Loop B
not included that String, but in the loop there is break
statement that not available in scala. In loop C, I used for
statement, but with behaviour that very differents with for
loop in scala. My main concern is not to Include "pengkor"
String in the StringBuilder and not to load All content of the file to Scala List (for the purpose of List comprehension in scala or some other list operation) because the size of file.
public class TestDoWhile {
public static void main(String[] args) {
String s[] = {"makin", "manyun", "mama", "mabuk", "pengkor", "subtitle"};
String m = "";
StringBuilder builder = new StringBuilder();
// loop A
int a = 0;
while (!m.equals("pengkor")) {
m = s[a];
builder.append(m);
a++;
}
System.out.println(builder.toString());
// loop B
a = 0;
builder = new StringBuilder();
while (a < s.length) {
m = s[a];
if (!m.equals("pengkor")) {
builder.append(m);
} else {
break;
}
a++;
}
System.out.println(builder.toString());
// loop C
builder = new StringBuilder();
a = 0;
for (m = ""; !m.equals("pengkor"); m = s[a], a++) {
builder.append(m);
}
System.out.println(builder.toString());
}
}
Upvotes: 1
Views: 2780
Reputation: 11107
You can easily define a function and continue
instead of breaking
@tailrec
def continue(buf: Array[Byte]) {
val read = in.read(buf);
if (read != -1) {
sb.append(parse(buf, read))
continue(buf); // recur
}
// else do not recur = break the loop
}
continue(Array.fill(1)(0))
The logic is inverted: instead of breaking, you call the function for next iteration. The overhead is that you need to define a function and call it. As an advantage, you can give a semantic name to your loop, functionally pass arguments instead of updating variables and reuse the loop.
Upvotes: 0
Reputation: 5768
One way to do this is with a boolean as a condition in the loop.
val lines = Source.fromPath("myfile.txt").getLines()
val builder = new StringBuilder
var cond = true
while(lines.hasNext && cond) {
val line = lines.next
if(line != "pengkor") {
builder ++= line
} else cond = false
}
//.. do something with the builder
One more scala-like way is to use takeWhile
.
val lines = Source.fromPath("myfile.txt").getLines()
val builder = new StringBuilder
lines.takeWhile(_ != "pengkor").foreach(builder ++= _)
You can also have a look here: How do I break out of a loop in Scala? to see other ways of dealing with breaking out of a loop
Upvotes: 5