Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Gaurang Kotasthane
Gaurang Kotasthane
1,394 Points

Exception in thread "main" java.lang.NullPointerException at MyClas.main(MyClas.java:6) ERROR

this is my code

import java.io.Console;

class MyClas { public static void main(String[ ] args) { Console console = System.console(); String name = console.readLine("name is "); console.printf("%s is your name",name);

} }

when I run this code in eclipse [ since workspace aren't working currently ] I keep getting this error Exception in thread "main" java.lang.NullPointerException at MyClas.main(MyClas.java:6) ERROR

3 Answers

Hi Gaurang,

You can use the following with scanner.

import java.util.Scanner;

public class Main {

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    System.out.println("name is ");

    String name = scanner.nextLine();

    System.out.println(name + " is your name");


}

}

Geovanie Alvarez
Geovanie Alvarez
21,500 Points

You can use Scanner in eclipse and work the same :p

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Name is: \n");
        String name = scanner.nextLine();

        System.out.printf("%s is your name.", name);
    }
}
Jonathan Hector
Jonathan Hector
5,225 Points

Try removing the String in console.readLine. You don't need to write a String inside the readLine method. It's part of the Utility package.

Scanner class is more powerful as suggested by Joshua and Geovanie but I still put an answer for you just in case.

Console console = System.console();

System.out.prinln("What is your name");
String name = console.readLine();
console.printf("%s is your name", name);