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/

avatar ankitdixit
@ankitdixit

2 Kontribusi 0 Poin

Diperbarui 7 bulan yang lalu

2 Jawaban:

<div>This online compiler <a href="https://www.interviewbit.com/online-java-compiler/">https://www.interviewbit.com/online-java-compiler/</a></div>

avatar ankitdixit
@ankitdixit

2 Kontribusi 0 Poin

Dipost 2 tahun yang lalu

<div>Untuk Menghilangkannya , kamu harus memberikan nilai default pada variabel nama terlebih dahulu , kamu tambahkan di posisi paling atas. <br><br>&nbsp; &nbsp; <strong>if</strong> (name == <strong>null</strong>) {</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "No console available");</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <strong>return</strong>;</div><div>&nbsp; &nbsp; &nbsp; &nbsp; }<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>

avatar IYBLux
@IYBLux

6 Kontribusi 0 Poin

Dipost 2 tahun yang lalu

Login untuk ikut Jawaban