Error printing a single variable

Asked

Viewed 56 times

0

I am unable to print an ultra simple code in Java. It shows the following error:

Exception in thread "main" java.lang.Error: Unresolved Compilation problem: Cannot make a Static Reference to the non-static field dou at Excript_variables.main(Excript_variables.java:10)

The code:

public class Variaveis {

    int inteiro = 10;
    //float flo = 5.9;
    double dou = 3.8;
    String texto = "Oi";

    public static void main(String[] args) {
        System.out.println(dou);
    }
    }

Thank you!

1 answer

2


The variables belong to the Variables object, so you need to create an instance of it to access the variables in the instance OR change the variables to static:

Option 1: Creating the instance

public class Variaveis {

    int inteiro = 10;
    //float flo = 5.9;
    double dou = 3.8;
    String texto = "Oi";

    public static void main(String[] args) {
        System.out.println(new Variaveis().dou);
    }
}

Option 2: Static variables

public class Variaveis {

    static int inteiro = 10;
    //float flo = 5.9;
    static double dou = 3.8;
    static String texto = "Oi";

    public static void main(String[] args) {
        System.out.println(dou);
    }
}
  • 1

    For a moment of distraction, I hadn’t noticed the question of static context. + 1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.