所以我正在创建一个包含数组等的简单程序,并且我的程序可以完美编译。但是,当我运行它并输入文件名(航类)时,我的程序给出了错误 NoSuchElementException
我通过以下代码找出 System.in 是否可用进行了更深入的研究:
System.out.println(System.in.available());
这是我的相关代码的其余部分:
import java.util.Scanner;
import java.io.*;
public class FlightAirportController
{
public static void main(String[] args) throws IOException
{
Scanner input = new Scanner(System.in);
System.out.print("Please name the Input File: ");
System.out.println(System.in.available()); // checks if System.in is working: output is either 0 or 1.
Scanner fileScanner = new Scanner(new File(input.next() + ".txt"));
fileScanner.useDelimiter(", |\n");
}
}
最佳答案
System.out.println(System.in.available());
该行始终打印零,因为您无法根据需要更快地写入文本。
如果您在此行工作之前写入文本(非常几毫秒),则会打印 1。
new File(input.next() + ".txt")
Scanner.next()
返回文本直到第一个空格。如果文件名包含空格,您必须使用 Scanner.useDelimiter(pattern)
设置分隔符。
Scanner.next throws NoSuchElementException - if no more tokens are available.
解决方案:
使用方法Scanner.hasNext()
- 如果 inputStream 包含要读取的字符,则返回 true;否则返回 false。
如果需要读取Line,请使用Scanner.hasNextLine()
和Scanner.nextLine()
关于java - System.in 无法与 Scanner 配合使用 (NoSuchElementException),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47236817/