[英]System.in is not working with Scanner (NoSuchElementException)
So I'm creating a simple programme that contains arrays and such, and my programme compiles perfectly. 因此,我正在创建一个包含数组等的简单程序,并且我的程序可以完美地编译。 However, when I run it and input the name of my file (flight), my programme gives me the error
NoSuchElementException
I delved deeper by finding out whether System.in was available through the following code: 但是,当我运行它并输入文件名称(运行)时,程序通过以下代码找出System.in是否可用,从而给我带来了
NoSuchElementException
错误:
System.out.println(System.in.available());
This is the rest of my relevant code: 这是我相关代码的其余部分:
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());
This line always print zero, becose you can't write text so faster as needed. 该行始终显示为零,因为您不能根据需要更快地编写文本。
1 will print in case you write text before this line work (very few milliseconds). 如果您在此行之前输入文本,将打印1(几毫秒)。
new File(input.next() + ".txt")
Scanner.next()
return text until first space. Scanner.next()
返回文本,直到第一个空格为止。 If file name contains space you mast set delimeter with Scanner.useDelimiter(pattern)
. 如果文件名包含空格,则可以使用
Scanner.useDelimiter(pattern)
设置距离。
Scanner.next throws NoSuchElementException - if no more tokens are available.
Scanner.next抛出NoSuchElementException-如果没有更多标记可用。
Solution: 解:
use method Scanner.hasNext()
- return true if inputStream contains character to read/ false - in otherwise. 使用方法
Scanner.hasNext()
-如果inputStream包含要读取的字符,则返回true;否则返回false。
If you need read Line, use Scanner.hasNextLine()
and Scanner.nextLine()
如果需要读取Line,请使用
Scanner.hasNextLine()
和Scanner.nextLine()
You are missing the file location. 您缺少文件位置。
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
Will come when you are calling next
even if the Scanner
has no next element to provide. NoSuchElementException
将在您next
调用时出现,即使Scanner
没有要提供的下一个元素。 Instead of file.next()
use of file.hasNext()
will be helpful. 代替
file.next()
使用file.hasNext()
会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.