-1

I'm getting on learning Java for work, but even the most simplistic "hello world" script I can't get to run for some reason. Here is the code:

import java.io.Console;

class test2 {
    public static void main(String[] args) {
        Console console = System.console();
        console.printf("Test");
    }
}

I'm running this using IntelliJ, and the error I'm getting from the console is

Exception in thread "main" java.lang.NullPointerException
    at test2.main(testclass.java:6)

My research is basically showing that the printf method is a "newer" (and I'm saying that with a bit of sarcasm) method, but that was only with versions 1.5 and up (don't quote me on that).

I've tried to find the answer as to why I'm getting this error, but nothing is pointing me in the right direction. Any and all help on this is greatly appreciated!

1 Answers1

0

From my experience Console rarely works inside of IDEs. It would work if you were running the program from a CLI, just not while you're building it. However, your code should work fine if you use Sys-outs (as I call them) to provide output.

In other words, these lines:

Console console = System.console();
console.printf("Test");

Can be scrapped and changed to this:

System.out.println("Test"); 

UPDATE

A quick search landed me on this page which explains why Console doesn't typically work in IDEs and solutions: https://stackoverflow.com/a/26473083/8972283

Francis Bartkowiak
  • 1,374
  • 2
  • 11
  • 28
  • Oh wow, thank you! I tried googling but trying to learn and drinking at 11pm wasn't the best idea to be efficient ;) I was able to use System.out last night, but I could never explain the difference. Thanks a million for sharing :) – Eric Fuller Jan 16 '18 at 12:42