Error declaring Java constants

Asked

Viewed 45 times

0

I have just started my studies in Java and I have a problem declaring a constant:

class Ex007
{
    public static void main(String[] args)
    {
        float comprimento, raio = 9f;
        public static final float PI = 1.1416f;
        comprimento = raio * PI * 2f;
        System.out.println("Comprimento: " + comprimento);
    }
}

The following error appears:

ex007.java:6: error: illegal start of expression
        public static final float PI = 1.1416f;
        ^
ex007.java:7: error: <identifier> expected
        comprimento = raio * PI * 2f;
                   ^
ex007.java:8: error: <identifier> expected
        System.out.println("Comprimento: " + comprimento);
                          ^
ex007.java:8: error: illegal start of type
        System.out.println("Comprimento: " + comprimento);
                           ^
ex007.java:10: error: class, interface, or enum expected
}
^
5 errors

If in that code I remove the:

public static final

PI becomes a normal variable and the code works normally. All the tutorials about constants show that to declare just put the code:

public static final float NOME_CONSTANTE VALOR;

But that doesn’t work here, I tried to compile in replt.it to see if it wasn’t my JDK and there also didn’t work.

1 answer

1


In fact it is the following, as Voce is in the main method, Voce cannot define public attributes, and therefore within a (main) method Voce cannot define class attributes(Static). That is, if you take out the public and Static will work. Another question is this part: float length, radius = 9f; You are trying to inform 2 variables at the same time: length and radius, but Voce must inform one at a time.

Browser other questions tagged

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