问题描述
作为更大作业的一部分,我被指示读取用户输入的包含以下数据的 .date 文件路径。
e 2
b 1
a 3
h 5
c 4
通过链表函数运行后,该列表应该在控制台中显示为“海滩”。这是我遇到困难的代码片段。
do {
Scanner scnr = new Scanner(system.in);
System.out.print("Enter the secret file name: ");
String filename = scnr.nextLine();
File inputFile = new File(filename);
Scanner reader = new Scanner(inputFile).useDelimiter("\\/");
while (reader.hasNextLine()) {
//String line = reader.nextLine();
//int val = reader.readInt();
}
System.out.print("Ready to play? (no to quit): ");
userDecision = scnr.nextLine();
} while (!userDecision.equalsIgnoreCase("no"));
我认为将文件作为字符解析为字符串会更好,但我不知道该怎么做。是的,我知道这是一个愚蠢的问题。
解决方法
如 Andy 所写,next()
用于读取字符串,而 nextInt()
读取整数。
nextLine()
从当前位置读取余数,直到行尾。在整数之后,余数是换行符,这解释了为什么您的尝试没有按预期工作。