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
Fabian Rodriguez
Courses Plus Student 859 PointsNullPointerException
package javaapplication2;
import java.io.Console;
public class JavaApplication2 { public static void main(String[] args) { Console console = System.console();
String yourName = console.readLine("Write your name here: ");
console.printf("Hi, %s %n, it's great to have you here", yourName);
}
}
2 Answers
Patrik Horváth
11,110 PointsIf this is JAVA you should use "+" to Combine Strings so
I dont recommended using Console because it not supported by IDEs but OKey :) maybe your lern java for android :)
console.printf("Write your name here:"); // you post msng for user in CONSOLE
String yourName = System.console().readLine(); // i will wait on your input :D
console.printf("Hi, %s %n, it's great to have you here" + yourName); // you print output
Sławomir Lasik
7,792 PointsYour code is compiling and running. Try to run it again
It may direct to null only when no console is available to give for the Current JVM.
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.
to check for this option try this
import java.io.Console;
import java.lang.NullPointerException;
public class JavaApplication2 {
public static void main(String[] args) {
Console console = null;
try{
console = System.console();
if(console== null) {
throw new NullPointerException();
}
}catch(NullPointerException e){
System.out.printf("NullPointerException catched! No console avaible for this JVM%n");
}
String yourName = console.readLine("Write your name here: ");
console.printf("Hi, %s %n, it's great to have you here", yourName);
}
}
Fabian Rodriguez
Courses Plus Student 859 PointsFabian Rodriguez
Courses Plus Student 859 PointsThank you very much, so instead of using console, what should I use? If I'm using IDE
Patrik Horváth
11,110 PointsPatrik Horváth
11,110 PointsSystem.out for Output and System.in for Input for example
System.out.println("YOUR StRING or StRING OBJECT");
System.in.Scanner(); // this is good for looping in WHILE until you press enter fo example :)