我正在输入一个txt文件,这是一个缩短的版本
10
"Alexander McCall Smith" "No. 1 Ladies' Detective Agency"
我运行这段代码:
Scanner in = new Scanner(new File(newFile + ".txt"));
int size = in.nextInt();
String inputLine = in.nextLine();
size 最终为 10,但 inputLine 最终什么也没收到。我收到错误
Exception in thread "main" java.util.NoSuchElementException: No line found.
我去了调试器,它说一个位置为 (-1, -1) 的字符串是 java 尝试插入 inputLine 的内容。
我不知道为什么,我知道有 50 多行10 点后的文本。我运行了 in.next()
并且效果很好。有谁知道为什么?
我也运行此代码:
inputLine.trim();
int posn = inputLine.indexOf('\"');
int nextPosn = inputLine.indexOf('\"',posn + 1);
String author = inputLine.substring(posn, nextPosn);
最佳答案
安德鲁·李说得对。调用 nextInt
不会消耗该行,因此您仍在第一行,即带有“10”的行。
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(Test.class.getResourceAsStream("input.txt"));
int size = in.nextInt();
String inputLine = in.nextLine();
System.out.println(size); // prints "10"
System.out.println(inputLine); // prints nothing
inputLine.trim();
int posn = inputLine.indexOf('\"');
int nextPosn = inputLine.indexOf('\"', posn + 1);
String author = inputLine.substring(posn, nextPosn); // Throws: "java.lang.StringIndexOutOfBoundsException: String index out of range: -1"
}
如果您连续调用 nextLine
两次,您将得到“Alexander”线路。
(我不知道您在哪里得到 NoSuchElementException
。它一定来自程序中的其他地方。)
关于java - 未找到线路 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40188505/