string – Java end of file

string – Java end of file

If youd like to scan from a file, you can use the below code.

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) throws FileNotFoundException {
        Scanner scan = new Scanner(new File(input.txt));
        int counter = 1;
        while (scan.hasNextLine()) {
            String line = scan.nextLine();
            System.out.println(counter +   + line);
Scanner line = new Scanner(); // <-- YOUR ERROR - there is no constructor for the Scanner object that takes 0 arguments. 
// You need to specify the environment in which you wish to scan. Is it the IDE? A file? You need to specify that.

Since you said EOF, Im assuming there is a File associated with this task.

Create a File object, toss that into the Scanner constructor.

File readFile = new File(PATH_TO_FILE); // where PATH_TO_FILE is the String path to the location of the file
// Set Scanner to readFile
Scanner scanner = new Scanner(readFile);

You also have a duplicate local variable named: line

I suggest you do more reading to get a grasp of how variables and objects work rather than guess or be spoonfed code you dont understand. Thats how you become a strong programmer.

string – Java end of file

Documentation states that you need to pass Source to Scanner, so that it can scan from it.

To get user input then you need to use Scanner(InputStream source) constructor.

Scanner line = new Scanner(;

public static void main(String[] args) {
    Scanner line = new Scanner(; // Added source parameter in constructor.
    int counter = 1; // Initialization of counter is done outside while loop, otherwise it will always get initialized by 1 in while loop
    while (line.hasNextLine()) {
        String lineStr = line.nextLine(); // changed variable name to lineStr, because 2 variable cant be declared with the same name in a method.
        System.out.println(counter +   + lineStr);

Note: Make sure you break your while loop, otherwise it will go into infinite loop.

Leave a Reply

Your email address will not be published.