Reputation: 11
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.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");
}
}
Upvotes: 1
Views: 331
Reputation: 383
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. Instead of file.next()
use of file.hasNext()
will be helpful.
Upvotes: 0
Reputation: 221
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).
new File(input.next() + ".txt")
Scanner.next()
return text until first space. If file name contains space you mast set delimeter with Scanner.useDelimiter(pattern)
.
Scanner.next throws NoSuchElementException - if no more tokens are available.
Solution:
use method Scanner.hasNext()
- return true if inputStream contains character to read/ false - in otherwise.
If you need read Line, use Scanner.hasNextLine()
and Scanner.nextLine()
Upvotes: 1