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

Md shujaul Haque
Md shujaul Haque
839 Points

given code is not running public stat

import java.io.Console; import java.util.Random; /** *

  • @author Asus */ public class Loopy {

public static void main(String[] args) { Console console = System.console(); String[] sweetFlavors = {"Caramel", "Cinnamon", "Watermelon", "Baked Beans"}; String[] savoryFlavors = {"Sea Salt", "Potato Chip", "Carrot", "Barbeque Sauce"};

for( String sweet :sweetFlavors){

for(String savory:savoryFlavors){

    console.printf("%s and %s  %n" ,sweet,savory);

}

}

}} Exception in thread "main" java.lang.NullPointerException at Printer.printString(Printer.java:13) at Printer.print(Printer.java:9) at Printer.main(Printer.java:18) Command exited with non-zero status 1

1 Answer

Philipp Rรคse
PLUS
Philipp Rรคse
Courses Plus Student 10,073 Points

Dear Md shujaul Haque,

I tried the code you offered by myself. I think your problem is your Console class you set at your first line in your main method.

Have you a special purpose that you're using the "Console class"?

On my point of view this type of class has entered the java "universe" primarily for a better input-handling.

For a simple console output you better use the sout-command.

I tried it with a System.out.printf() and it works.

In the Java documentation was a refer to your ErrorException. They said:

If this virtual machine has a console then it is represented by a unique instance of this class which can be obtained by invoking the System.console() method. If no console device is available then an invocation of that method will return null.

...

Unless otherwise specified, passing a null argument to any method in this class will cause a NullPointerException to be thrown.

https://docs.oracle.com/javase/7/docs/api/java/io/Console.html

I hope I was right so far and it helps at least a bit :)