【发布时间】:2020-10-05 19:22:51
【问题描述】:
我正在尝试编写一个扫描器,以便每次检测到 \n 时,它都会扫描之后的行,直到出现新的 \n 为止。我第一次尝试这样的事情。
import java.util.Scanner;
public class test{
public static void main(String[] args) {
String input = "first line \nsecond line \nthird line";
Scanner sc = new Scanner(input);
while(sc.hasNextLine()) {
String stuff = sc.nextLine();
System.out.println(stuff);
}
sc.close();
}
}
哪个有效,输出是
first line
second line
third line
但是,当我尝试使用 Scanner(System.in) 做同样的事情时,即使使用相同的输入,它也不会以同样的方式工作
import java.util.Scanner;
public class test{
public static void main(String[] args) {
System.out.println("Please enter things");
Scanner cmd = new Scanner(System.in); //input: "first \n second \n third"
String input = cmd.nextLine();
Scanner sc = new Scanner(input);
while(sc.hasNextLine()) {
String stuff = sc.nextLine();
System.out.println(stuff);
}
cmd.close();
sc.close();
}
}
输出:
first \n second \n third
我应该改变什么,以便每个 \n 都会打印一个新行?
编辑: 如果输入是
first
second
third
立即进入提示,scanner.nextLine() 就够了吗?
【问题讨论】:
-
如果
//input: "first \n second \n third"表示您实际上是在控制台输入first \n second \n third,那么您的控制台会将\n视为两个 单独的字符:\和@987654330 @ NOT 作为行分隔符。但是你想在这里做什么?如果您尝试提供 3 行,请像line1[press enter]line2[press enter]line3[press enter] 那样做(现在您需要决定什么应该停止循环,如果它在 N 之后停止行,或在用户提供的某些特定文本之后,例如“end”“bye”)。 -
@Pshemo 是的,我想一口气输入所有内容。我不知道
\n被视为两个字符,谢谢通知我!那么如果我同时输入它们,我将如何拆分first line \nsecond line \nthird line?我了解如何逐行输入命令,但这不是我想要在这里做的。 -
不要这样输入。如果您的文本实际上将包含
\n,其中应该代表两个字符,例如my file is at c:\my\new\folder?如果您想将大量数据传递给应用程序,那么可以将其存储在文件中,然后将该文件的位置作为参数传递? -
@Pshemo 我明白你在说什么,但选择真的不取决于我:(我正在为作业写它,我们的教授说输入格式将是行分隔的通过换行符/返回变量。
-
我不确定您所说的“输入格式中的“变量”将是由换行符/返回 变量 分隔的行”。无论如何,如果输入将提供实际的行分隔符,那么
nextLine()应该能够正确处理它。