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


Jawaban

avatar ankitdixit

@ankitdixit

2 Kontribusi 0 Poin


Untuk Menghilangkannya , kamu harus memberikan nilai default pada variabel nama terlebih dahulu , kamu tambahkan di posisi paling atas.

    if (name == null) {            System.out.println(                "No console available");            return;        }

==============
atau coba
String name =" " ;
 name = System.console().readLine();

        System.out.println("You entered string " + name);
avatar IYBLux

@IYBLux

5 Kontribusi 0 Poin


Login untuk gabung berdiskusi
premium logo tube

Hey, sedang ada diskon premium untuk akses semua kelas. Lihat di sini