gpt4 book ai didi

java - 我的代码给了我一个 no such element 异常

转载 作者:太空宇宙 更新时间:2023-11-04 15:02:12 25 4
gpt4 key购买 nike

public static void getBooks()throws FileNotFoundException{

Scanner input = new Scanner(bookFile);
String line = input.nextLine();
int bookNum = 1;

while (input.hasNextLine()) {
bookNum += 1;
line = input.nextLine();
}
input.close();

input = new Scanner(bookFile);
line = input.nextLine();

bookarray = new String[3][bookNum];

for (int y = 0; y < bookNum; y++){
bookarray [0][y] = line.substring(0,10);
bookarray [1][y] = line.substring(11,15);
bookarray [2][y] = line.substring(17,18);
line = input.nextLine();
}

}

这段代码给了我这个错误:

Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at BookInventory1.getBooks(BookInventory1.java:64)
at BookInventory1.main(BookInventory1.java:15)
ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
JDWP exit error AGENT_ERROR_NO_JNI_ENV(183): [../../../src/share/back/util.c:838]

指向最后

  line = input.nextLine();

线。谁能帮我吗?

最佳答案

你应该检查 -> input.hasNext()

查看本教程 scanner example或阅读javadoc或查看 next () 的特定 javadoc

NoSuchElementException - if no more tokens are available

例如:

public static void getBooks()throws FileNotFoundException{

Scanner input = new Scanner(bookFile);
String line = input.nextLine();
int bookNum = 1;

while (input.hasNextLine()) {
bookNum += 1;
line = input.nextLine();
}
input.close();

input = new Scanner(bookFile);
if(scanner.hasNextLine(){
line = input.nextLine();

bookarray = new String[3][bookNum];

for (int y = 0; y < bookNum; y++){
bookarray [0][y] = line.substring(0,10);
bookarray [1][y] = line.substring(11,15);
bookarray [2][y] = line.substring(17,18);
if(!line.hasNextLine()){break;}
line = input.nextLine();
}
}

}

关于java - 我的代码给了我一个 no such element 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22448802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com