Sunday, 15 May 2011

java - Error of static and non-static -



java - Error of static and non-static -

i'm confused between when utilize public static void xxx() , public void xxx(). error i'm getting in main class.

generaterandomnumber();

the error : (error: non-static method generaterandomnumber() cannot referenced static context)

getuserinput();

he error : (error: non-static method getuserinput() cannot referenced static context)

getresult();

the error : (error: non-static method getresult() cannot referenced static context)

public class highlowgame { int randomnumber; int guess; public void generaterandomnumber(){ randomnumber = (0+(int)(math.random() * ((0 - 99) + 1))); } public void getuserinput(){ guess = integer.parseint(joptionpane.showinputdialog( null, "plaese input")); } public string getresult(){ if(randomnumber<guess){ homecoming "your number bigger magic number"; } else if (randomnumber>guess) { homecoming "your number smaller magic number"; } else { homecoming "you correct! "+randomnumber; } } public static void main(string[] args){ generaterandomnumber(); getuserinput(); getresult(); }

}

you cannot access non-static instance method/variable static context directly. need instance of class access them .

public static void main(string[] args){ highlowgame ref = new highlowgame (); ref. generaterandomnumber(); ref.getuserinput(); ref.getresult(); }

or can create these methods static , access them directly. create methods static when think instances of class should share date/methods.

java

No comments:

Post a Comment