-1

Result is: Error.I think that console is null,I don't know why.Can somebody help me?

import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;

public class Vezbanje {   
    public static void main(String[] args) {   
        Console console = System.console();

        if(console != null) {
            console.printf("Please enter your username: ");
            String username = console.readLine();
            console.printf(username + "\n");

            console.printf("Please enter your password: ");
            char[] passwordChars = console.readPassword();
            String passwordString = new String(passwordChars);

            console.printf(passwordString + "\n");
        } else {
            System.out.print("Error");
        }
    }
}
Crazyjavahacking
  • 9,343
  • 2
  • 31
  • 40
Nicolas
  • 13
  • 2
  • possible duplicate of [System.console() returns null](http://stackoverflow.com/questions/4203646/system-console-returns-null) – TDG Jul 25 '15 at 08:48
  • You can create a Scanner object try reading from console `Scanner scanner = new Scanner(System.in); scanner.nextLine();` Instead of doing `console.readLine();` – dev Jul 25 '15 at 08:51

1 Answers1

0

It's because there is no console available.

From, System.console() documentation

Returns: The system console, if any, otherwise null.

It returns the console only if there's one. And not always there is a console.

For Eg: While running the code from Eclipse, you won't find a console and hence calling System.console() would return null.

Codebender
  • 14,221
  • 7
  • 48
  • 85