java - 未找到线路 - Java

标签 java

我正在输入一个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/

相关文章:

java - 自定义类加载器和 Java 代理

java - 何时有效地使用线程

java - 检查是否调用了 void 方法

java - 如何用commons-exec执行/bin/sh?

java - 在 .war 之外引用 configuration.properties

java - 以编程方式 RelativeLayout.ALIGN_RIGHT 与给定的 View.getId() 不工作

java - 每当我点击按钮时 Android 应用程序就会关闭

java - 使用 TCP/IP 套接字的多线程

java - 具有单个泛型方法的非泛型 Java 接口(interface),仅在左侧具有类型参数

java - 与其他类的数组 - 对象 - Java