Here is the solution to your problem.
Count the number of times that the condition isBlank()
is TRUE
consecutively
and BREAK
if maximum accepted.
public static void main(String[] args) {
final var MAXIMUM_LINE_TESTED = 2;
var counterTest = 0;
try (var sc = new Scanner(System.in)) {
final var al = new ArrayList<String>();
System.out.println("Enter text:");
while (true) {
final var line = sc.nextLine();
if (line.isBlank()) {
counterTest++;
if (counterTest >= MAXIMUM_LINE_TESTED)
break;
} else {
counterTest = 0;
}
al.add(line);
}
for (final String v : al) {
System.out.println(v);
}
}
}
Before update 26.02.21 :
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
The break statement can also be used to jump out of a loop.
by w3schools
You must use CONTINUE
so as not to exit the WHILE
. BREAK
stops the WHILE
if the condition is true
.
CONTINUE
:
public static void main(String[] args) throws Exception {
String s = "hello world!hello world!hello world!hello world!hello world!\n"
+ " \n"
+ "hello world!hello world!hello world!hello world!hello world!\n"
+ "hello world!hello world!hello world!hello world!hello world!\n"
+ "hello world!hello world!hello world!hello world!hello world!\n";
try (Scanner scanner = new Scanner(s)) {
String line = "", text = "";
while (scanner.hasNextLine()) {
line = scanner.nextLine();
if (line.isBlank()) {
System.out.println("skipped");
continue;
}
text += line + "\n";
}
System.out.println(text);
}
}
BREAK
:
public static void main(String[] args) throws Exception {
String s = "hello world!hello world!hello world!hello world!hello world!\n"
+ " \n"
+ "hello world!hello world!hello world!hello world!hello world!\n"
+ "hello world!hello world!hello world!hello world!hello world!\n"
+ "hello world!hello world!hello world!hello world!hello world!\n";
try (Scanner scanner = new Scanner(s)) {
String line = "", text = "";
while (scanner.hasNextLine()) {
line = scanner.nextLine();
if (line.isBlank()) {
System.out.println("skipped");
break;
}
text += line + "\n";
}
System.out.println(text);
}
}