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<noob />
17,062 PointsWhy i cant run this code in inteliji?
Hi, I have troubles with inteliji..
import java.io.Console;
public class CheckPassFail {
public static void main(String[] args) {
Console console = System.console();
String userInput = console.readLine("Please enter a number : ");
int number = Integer.parseInt(userInput);
if (number % 2 == 0) {
System.out.printf("%d is an even number !", number);
}
else {
System.out.printf("%d is a odd number!", number);
}
System.out.printf("Good bye!");
}
}
when i try to run this program i get nullPointerException
1 Answer
Brendan Whiting
Front End Web Development Techdegree Graduate 84,738 PointsI get a NullPointerException too, specifically on this line:
String userInput = console.readLine("Please enter a number : ");
So this means it's trying to do something but unexpectedly got a null value. I'm guessing that the console
object is the null value, so I added this line to print it out, and it is in fact null (could have also used the debugger in IntelliJ).
Console console = System.console();
System.out.println(console); // null
String userInput = console.readLine("Please enter a number : ");
I googled "java.io.Console null pointer exception" and found this StackOverflow article which led me to this blog post about an issue with this console package and IDE's.
But those solutions looked a bit overly complicated to me, and there are other ways of getting input from the command line. I like the Scanner class, myself:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter a number: ");
String userInput = scanner.nextLine();
int number = Integer.parseInt(userInput);
if (number % 2 == 0) {
System.out.printf("%d is an even number !", number);
}
else {
System.out.printf("%d is a odd number!", number);
}
System.out.printf("Good bye!");
}
}