Postingan lainnya
How to avoid NullPointerException in Console class in Java?
I was reading an article on ways to read input from the user when I came across a method which said "Using Console Class."
// Java program to demonstrate working of System.console()
// Note that this program does not work on IDEs as
// System.console() may require console
public class Sample {
public static void main(String[] args)
{
// Using Console to input data from user
String name = System.console().readLine();
System.out.println("You entered string " + name);
}
}
When I tried to run the above code on an online, interactive compiler it's giving the error: Exception in thread "main" java.lang.NullPointerException at Sample.main(Sample.java:8)
Why is this happening?
I also tried to create an object of Console class and then call the .readLine() function but it gave me the same error.
Online compiler: https://www.interviewbit.com/online-java-compiler/
2 Jawaban:
<div>This online compiler <a href="https://www.interviewbit.com/online-java-compiler/">https://www.interviewbit.com/online-java-compiler/</a></div>
<div>Untuk Menghilangkannya , kamu harus memberikan nilai default pada variabel nama terlebih dahulu , kamu tambahkan di posisi paling atas. <br><br> <strong>if</strong> (name == <strong>null</strong>) {</div><div> System.out.println(</div><div> "No console available");</div><div> <strong>return</strong>;</div><div> }<br><br>==============<br>atau coba<br>String name =" " ;</div><pre> name = System.console().readLine();</pre><div><br></div><pre> System.out.println("You entered string " + name);</pre>