Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

General Discussion

Simple Java error with float

Hi guys, I am doing some simple Java programming.

I am having an issue with the float while using

System.out.println

I am using the Terminal to run my Java programmes.

So here is the code

class simplejava
{
    float d = 8.8f;
    float b = 1.98f;
    float p = 63.23f;

    public static void main (String [] args) 
    {
        System.out.println( d + b + p );   
    }

}  

I am getting errors on all three of the floats

Here is the float errors that the Terminal gives out.

simplejava.java:9: non-static variable d cannot be referenced from a static context System.out.println( d + b + p );
^ simplejava.java:9: non-static variable b cannot be referenced from a static context System.out.println( d + b + p );
^ simplejava.java:9: non-static variable p cannot be referenced from a static context System.out.println( d + b + p );
^ 3 errors

Thank you for any help with this guys!

Also, sorry if this post is not in the write place. I though putting this in the Android post would not really be the right place!

1 Answer

Your main function is static and your variables are not static. You can't access a non-static member variable from a static method. You can fix that error by making all of your member variables static.

For this little example, it's fine to fix the problem by making all of the member variables static However, in a real program, you probably wouldn't want to do that. It's best to put all of the actual program logic inside other classes that don't use static members and static methods very often. For example, you could do it like this to avoid using static members:

public class MyClass
{
   float d = 8.8f;
   float b = 1.98f;
   float p = 63.23f;

   public void printMembers()
   {
       System.out.println( d + b + p );   
   }
}

class simplejava
{
    public static void main (String [] args) 
    {
        MyClass myClass = new MyClass();
        myClass.printMembers(); 
    }
}  

Thanks Ben!