0

HI all I'm pretty new to this and just got hold of the instance and static variables.What i want to do is declare something inside as a static variable use it inside that class , assign a value to it by a user input , and do a calculation using that input and send this input inside another class (which doesn't have the main method ) and use it inside an array. Is it possible ? if so how ? from the way i did it it says that the variable can not be identified so obviously im wrong.I know i can do this using setter and getter but i dont know how to do so .Thank you so much in advance.What i have so far

  public class Character {

       public static int amount =0;

       public void calculate(){

       amount=sc.nextInt();

       if(amount<0){
                 System.out.print("You are broke");
                       }
        else{
              System.out.print("You are ok You have"+amount);
            }
  }

Inside another class i want to use this amount

public class calculation2{

    int [] arr=new int[amount];

    public void smile(){

      bla bla bla bla

     }
}

How can i go about this , what am i dointwrong and any suggestions to fix it ? thank you so mumch

2
  • 4
    Public static variables are generally considered to be terrible design, because of the fact that you have absolutely no control over how they are used (or abused). You should really re-think what you're trying to solve here. Commented Apr 7, 2018 at 16:42
  • 2
    you can access it by Character.amount. Commented Apr 7, 2018 at 16:43

2 Answers 2

1

Since it is static, you can refer to the static amount variable in calculation2 by doing this:

int [] arr=new int[Character.amount];

public void smile(){

  System.out.println(Character.amount);

 }

though you shouldn't code like that. Use static when something has an actual value or return value and you want to use that in another class.

Sign up to request clarification or add additional context in comments.

Comments

0

This is not right way of coding: However in your code, you ave declared static variable as amount as public, so you can access it in smile method as:

int [] arr=new int[Character.amount];    
public void smile(){
      System.out.println(Character.amount);
     }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.