0

I want to input a name and to print the first char ....

public class Test {

    public static void main(String[] args) {

        Console console = System.console();
        System.out.println("Type your name : ");
        String inputChar = console.readLine();

        char firstChar = inputChar.charAt(0);

        System.out.println(firstChar);



    }
}
Razib
  • 10,965
  • 11
  • 53
  • 80
  • 2
    provide the stack trace where are you getting a NPE. Did you put a debugger on your code? – underdog May 06 '15 at 04:16
  • [Sometimes `Console` class acts as a surprise to people when they run their code in an IDE.][1] [1]: http://illegalargumentexception.blogspot.com/2010/09/java-systemconsole-ides-and-testing.html – Jude Niroshan May 06 '15 at 06:01

2 Answers2

2

Some IDEs will return NPE for Console class. you can use the Scanner class and do it easily:

try this:

      Scanner scan = new Scanner(System.in);
      System.out.println("Enter a Name:");
      String s = scan.next();
      System.out.println(s.charAt(0));

this will print the first letter of your input String.

Nomesh DeSilva
  • 1,649
  • 4
  • 25
  • 43
1

Using the Console class can a bit unreliable at times.

For reading console input, it would be preferrable to use either the Scanner class or a BufferedReader. You can use a Scanner like :

Scanner scanner = new Scanner(System.in); // System.in is the console's inputstream
System.out.print("Enter text : ");
String input = scanner.nextLine();
// ^^ This reads the entire line. Use this if you expect spaces in your input
// Otherwise, you can use scanner.next() if you only want to read the next token
System.out.println(input);

You can also use BufferedReader like :

pre Java 7 syntax

try {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter text : ");
        String input = br.readLine();
        System.out.println(input);
        br.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

Java 7 syntax

try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {

        System.out.print("Enter text : ");
        String input = br.readLine();
        System.out.println(input);

    } catch (Exception e) {
        e.printStackTrace();
    }

Note: You need to use a try-catch statement when calling br.readLine() because it throws an IOException.

You can use Scanner if you want to read tokens (chunks of text separated by spaces). Use a BufferedReader if you want to simply read from the InputStream.

Lexicographical
  • 501
  • 4
  • 16