Search code examples
javajava.util.scannersublimetext

Java with Sublime Text - Scanner not working?


I am trying to learn Java, and I've just started. I want to run this code I found online:

import java.util.Scanner;  // needed for Scanner

/** A Java program that demonstrates console based input and output. */
public class MyConsoleIO 
{
    // Create a single shared Scanner for keyboard input
    private static Scanner scanner = new Scanner( System.in );

    // Program execution starts here
    public static void main ( String [] args )
    {
        // Prompt the user
        System.out.print( "Type some data for the program: " );


        // Read a line of text from the user.
        String input = scanner.nextLine();

        // Display the input back to the user.
        System.out.println( "input = " + input );

    } // end main method

} // end MyConsoleIO class

However I get this error:

Type some data for the program:
Exception in thread "main" java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Scanner.java:1540)
    at MyConsoleIO.main(MyConsoleIO.java:17)
[Finished in 0.9s with exit code 1]

I am running the code in Sublime Text 2, directly in the editor, pressing CMD+B.


Solution

  • I'm not sure about Sublime Text, but your program looks correct. I ran it in my NetBeans 8.0.1 and all works fine. It looks like it is a problem in how Sublime runs java programs.

    Try compile and run it with standard java compiler and run tools. For further details read this: http://www.oracle.com/technetwork/java/compile-136656.html

    See also: https://stackoverflow.com/a/14810204/1981450