Error when printing a simple variable

0

I'm not able to print ultra-simple code in Java. You acknowledge the following error:

  

Exception in thread "main" java.lang.Error: Unresolved compilation problem:       Can not make a static reference to the non-static field 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!

    
asked by anonymous 24.02.2017 / 14:36

1 answer

2

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: Instance Creation

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);
    }
}
    
24.02.2017 / 14:38