[英]Scanner not reading the next line over and exiting loop
嗨,我正在做一个程序,该程序允许用户将数据段落插入扫描仪输入,并且我有一个循环来检查下一行是否为空白,但我希望它检查下 2-3 行的文本,因为它段落时自动退出
编码:
String tex ="";
String line;
while (in.hasNextLine()) {
line = in.nextLine();
if (line.isEmpty()) {
break;
}
tex += line + "\n";
}
我会添加另一个 if 语句吗? 还是有更有效的方法来获得我正在寻找的所需 output? 我希望能够将一两个段落发布到扫描仪中(我将扫描仪用于更大的目的)而无需预先终止。
这是您的问题的解决方案。
计算条件isBlank()
连续为TRUE
的次数,如果接受最大值则为BREAK
。
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);
}
}
}
如果出现指定条件, continue 语句会中断一次迭代(在循环中),并继续循环中的下一次迭代。
break 语句也可以用来跳出循环。
您必须使用CONTINUE
以免退出WHILE
。 如果条件为true
, BREAK
停止WHILE
。
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);
}
}
经过几个小时寻找解决方案,这就是我能够解决问题的方法。 防止scanner.nextLine(); 从退出 while 循环,您需要复制它。 添加另一个 Scanner.nextLine(); 到while循环结束。
String tex ="";
String line;
while (true) {
line = in.nextLine();
if (line.isEmpty()) {
break;
}
tex += line + "\n";
in.nextLine()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.