gpt4 book ai didi

java - 调用 .next() 方法时扫描仪出现 NoSuchElementException

转载 作者:行者123 更新时间:2023-12-01 18:49:59 26 4
gpt4 key购买 nike

在 Java 中,我收到此异常:

Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at com.reading.text.Activity3.readFile(Activity3.java:22)
at com.reading.text.Activity3.main(Activity3.java:10)

来自此 Java 代码:

public static void main(String args[])
{
readFile("C:/Users/forsakendoll/Desktop/boom.txt");
}

public static void readFile(String path) {
Scanner file = null;
try {
file = new Scanner(new File (path));
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
while (file.hasNext()) {
for(int counter = 0 ; counter < file.next().length(); counter ++) {
System.out.println(file.next().charAt(counter));
}
}
}
}

抛出异常

System.out.println(file.next().charAt(counter));

异常是什么意思?

最佳答案

您在循环的每次迭代中都会调用 .next() 两次,因此当您接近末尾时,您会跳出列表的末尾,编译器会告诉您那里没有任何内容.

而不是这个:

for(int counter = 0 ; counter < file.next().length(); counter ++) {
System.out.println(`file.next()`.charAt(counter));
}

这样做:

String temp = file.next();
for(int counter = 0 ; counter < next.length(); counter ++) {
System.out.println(temp .charAt(counter));
}

SEE HERE

关于java - 调用 .next() 方法时扫描仪出现 NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16194834/

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