繁体   English   中英

System.in无法与Scanner一起使用(NoSuchElementException)

[英]System.in is not working with Scanner (NoSuchElementException)

因此,我正在创建一个包含数组等的简单程序,并且我的程序可以完美地编译。 但是,当我运行它并输入文件名称(运行)时,程序通过以下代码找出System.in是否可用,从而给我带来了NoSuchElementException错误:

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抛出NoSuchElementException-如果没有更多标记可用。

解:

使用方法Scanner.hasNext() -如果inputStream包含要读取的字符,则返回true;否则返回false。

如果需要读取Line,请使用Scanner.hasNextLine()Scanner.nextLine()

您缺少文件位置。

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

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("C:\\Users\\..\\"+input.next() + ".txt"));
      fileScanner.useDelimiter(", |\n"); 
    }
}

NoSuchElementException将在您next调用时出现,即使Scanner没有要提供的下一个元素。 代替file.next()使用file.hasNext()会有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM