• Post Reply Bookmark Topic Watch Topic
  • New Topic

non-static variable cant be referenced from a static context  RSS feed

 
Ben Hultin
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As I have been working on this program, I keep running into static issues. My latest static error is:




BenHultinProg2.java:29: non-static variable hw4 cannot be referenced from a stat
ic context
double totalPPoints = hw1.getPPoints() + hw2.getPPoints() + hw3.
getPPoints() + hw4.getPPoints();

^
BenHultinProg2.java:34: non-static variable lGrade cannot be referenced from a s
tatic context
lGrade = totalEPoints / totalPPoints;
^
BenHultinProg2.java:36: non-static variable lGrade cannot be referenced from a s
tatic context
if (lGrade >= 0.9) {
^




Trying to avoid static errors I have put a methods content into a the main method, which just created more static errors.

This is currently what I have now.



and my driven class is:



I appreciate any help in the matter
 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static methods/variable exist regardless of whether or not you create the object where they are defined.

Non-static methods/variables don't exist until you create an object.

So, if you try and use a non-static thing from a static context, the java compiler tells you 'Hey - that thing doesn't exist yet'.

on line 23 in your main, you create a new BenHultinProg2 object, but you don't SAVE it anywhere. So you have created all those HwScore objects, but they all get lost since there is no active reference anymore. you need to do something like this:

BenHultinProg2 myProg2 = new BenHultinProg2();

then you'll need to do this:

double totalEPoints = myProg2.hw1.getEPoints() + myProg2.hw2.getEPoints() + myProg2.hw3.getEPoints() + myProg2.hw4.getEPoints();
 
Ben Hultin
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks a lot for the help, I will definelty save that explanation of static and non-static variables. With that I was able to fix everything. My program now works and Im done with the assignment! Thanks again for the help.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!