Can I use non static variable in static method in java? -


"write program in java declare class 1 integer data member , 2 member functions in() , out() input , output data in data member."

my current code follows.

import java.util.scanner;  public class operator  {      static int a;     public static void input() {          scanner in=new scanner(system.in);          system.out.println("enter number:");          a=in.nextint(); //here problem      }      public static void output() {          system.out.println("number is:" + a);      }      public static void main(string[] args)      {         input();         output();     }  } 

you seemed confused w.r.t instance variables , local variables.

you can declare "local variable" inside static method. main() example static function , declare variables inside it.

so creation of variable "in" of type scanner inside input() function fine.

however, "cannot" access instance variables , instance methods static methods.

this post on stack overflow gives full , complete answer: can non-static methods modify static variables

as far code concerned, there's minor error in code. function call read integer "nextint" , not "nextint". java uses camel-case define methods. careful method usage.

the modified code should this:

class operator {     static int a;     public static void input() {          scanner in=new scanner(system.in);          system.out.println("enter number:");          a=in.nextint(); //this nextint , not nextint     }      public static void output() {          system.out.println("number is:" + a);      }      public static void main (string[] args) throws java.lang.exception     {         // code goes here         input();         output();      } } 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -