Why cant i access my static variable inside another class - java

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

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.

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);
}

Related

how to use variable value such as n or i in my Code?

I am a beginner in java & I have a question about this code , I am sorry that my question sounds a little bit stupid :)
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
In this code , inside the constructor the variable id has given this value i
and name = n
but in display() method I tried to use n & i like this
void display(){System.out.println(i+" "+n);}
but I got error :( !
so what's the point of giving the variable name a variable value such as n , if I can't use it at all ?
but in display() method I tried to use n & i like this
void display(){System.out.println(i+" "+n);}
They are the local to the constructor. You cannot access them. Their scope is limited to the constructor and not visible outside the constructor.
Try this:
void display(){System.out.println(id+" "+name);}
The variable id and name are will be accessible, because they are the class member which holds the data for a object.
A better way will be using them with the this reference.
void display(){System.out.println(this.id+" "+this.name);}
i and n are both parameters to the Student4 constructor. You cannot access these variables outside of the constructor. This is an issue related to scope. This is something you should read up on first as it is a very basic programming concept. See here:
http://java.about.com/od/s/g/Scope.htm
The scope of the variable i and n is inside the constructor of the class. So you cannot use it outside of your constructor.
In display method you want to print state of Student. So you should use class attributes i.e. id and name.
i and n are local variables of the constructor. So you can use them only inside constructor method (and not outside).

error: cannot assign a value to final variable (int)

Ok I'm sure this is simple, but I'm having issues and my mind is blank. =(
I know 'final' makes it so the variable can't change but that's pretty much all I can figure out about it right now.
And the code...
If I take out the 'final' the error comes up as "error: missing return statement
}" for the first two methods.
EDIT: Thank you all for the help, surprising how fast I got help!
So I just took out 'final' and added 'void' to the first two methods. I'm sure it'll take some time to fully understand everything, but it definitely helps.
There is a part two and here is the part that I have no clue on what to do...
The second part you just have to test this first program. Am I supposed to make a separate file with the same code?
If anyone can help great, but if not thats fine I'll work on it later.
You declare your function as
public static int removeOneFromRoom (int number)
{
totalNumber = totalNumber-number;
}
The emphasis here is the public static int, telling the compiler that your function is supposed to return an integer. You do however not return anything in that function body, so the compiler complains rightfully. Either return something, or declare the return value as void.
Maybe you're missing the return statement for the first two methods. Or you may want to change the return type to void if you don't need to return anything.
Doing these will remove your error but it might differ from what you need.
public static void addOneToRoom(int number)
{
numberInRoom = numberInRoom+number;
}
public static void removeOneFromRoom (int number)
{
totalNumber = totalNumber-number;
}
Hope this helps.
A variable declared with static and final keywords behaves like a constant. But what does that mean ?
It means you can't change their values. In simpler terms if variable is a primitive then you can't change its value but if its a reference variable then you can't change the reference to some other address.
So in your code, declaring numberInRoom and totalNumber variables as static and final is wrong
public static int numberInRoom=3;
public static int totalNumber=30;
public static int addOneToRoom(int number)
{
numberInRoom = numberInRoom+number;
}
public static int removeOneFromRoom (int number)
{
totalNumber = totalNumber-number;
}
Are you sure that you want these variables to be declared as static because such variables shall be shared by all instances of the concerned class. Please have a look at what does declaring variables as static and final means

Passing a value input from main method to a private variable

I am trying to pass a value from the main method and set it to a private variable. Here is the main method that's pertinent:
import java.util.*;
public class Experiment{
private static Extension extension=new Extension();
public static void main(String[] ars);{
Scanner input=new Scanner(System.in);
System.out.print("Enter the length: ");
int length=input.nextInt;
extension.messages(length); }
}
and here's what goes with it:
public class Extension{
private int theLength;
public void Extension(int length){
theLength=length; }
public void setLength(int length){
theLength=length; }
public int getLength() {
return theLength }
public void messages(int length){
System.out.println("theLength: "+theLength);
System.out.println("Length: "+getLength(); }
}
I added the extra display because I wanted to see if the value was getting passed on correctly. When I run it, I realize that it's not; both theLength and length are set to zero despite having input different numbers. Can anyone see what I'm doing wrong? I would sincerely appreciate a thorough answer (since I am just starting out).
You are not setting the private variable length. You should call the setLength(int length) method.
change to this
System.out.print("Enter the length: ");
int length=input.nextInt;
extension.setLength(length); // this will set the private variable
extension.messages(length);
This is a lesson in encapsulation. Your issue, as #salihrkc said, is that you're never actually setting the length variable which exists in your "Extension" object. If you try to print "length" as passed in to your object, you'll see it's getting there just fine.
You act on your object using the dot operator (e.g. extension.messages(length);, to call the messages method). The key points you should be realizing is that you cannot set the objects length by just doing extension.theLength = length;. This is because of the private modifier. Instead you should be using the "getter" and "setter" methods. These functions exist within your object and therefore access to the private variables, so you can do something like extension.setLength(length); and System.out.println(extension.getLength());
Check out the two sources I linked, they'll help.
Good luck.

Is static bad? How to remove static variables?

I have some code that I am working on. It's basically takes in user input and creates a directed graph. One person can travel one way, the other person the opposite. The output is the overlap of where they can visit.
I have most everything working the way that I want it to, but I am concerned with the use of static that I have. I don't seem to fully understand it and no matter where I look, I can't find out its exact use OR how to get rid of it.
Could someone please help me to understand what static is and why it would be helpful?
Also, would it be better to move most the code from MAIN to helper methods? If I do this I have to move all my variables from main to the top of the class and then they all have to be declared as static?!
The reason everything has to be static is because you aren't creating any objects. If you were to create an object by calling new in your main method, you could use non-static variables on that object. This isn't really a good place to give you a tutorial on why you might want to use object-oriented design; you can find one of those online to read (a commenter above gave a possible reference). But the reason everything has to be static is because it's all just running from the main method, which is always static in java. If you were to call new somewhere, you could use non-static variables.
Static makes a method or a variable accessible to all the instances of a class. It's like a constant, but for classes. To make it more easy to understand some code will do the work:
public class Example {
public static int numero;
}
public class Implementation {
public static void main (String args[]) {
Example ex1 = new Example();
Example ex2 = new Example();
Example.numero=10;
System.out.println("Value for instance 1 is: " + ex1.numero);
System.out.println("Value for instance 2 is: " + ex2.numero);
}
}
Running the follwing code will output:
Value for instance 1 is: 10
Value for instance 2 is: 10
Because you set the static variable numero (number in italian) to 10.
Got it?
It looks like a lot of your static methods (findNodeInList, etc) all take the ArrayList (which represents a map) as their first argument. So instead of having it static, you could have a class Map, which stores a list of nodes and has methods on them. Then the main method would read the input, but not have to manage any nodes directly. e.g:
class Map {
ArrayList<Node> nodes;
public void addNode(Node n) { nodes.add(n); }
public int findNodeInList(String s) { ... }
...
public static void main(String[] args) {
Map peggyMap = new Map();
Map samMap = new Map();
// Read the data
samMap.add(new Node(...));
}
}
This keeps all the stuff to do with nodes/maps well encapsulated and not mixed in with stuff to do with reading the data.
Static is useful if you going to be using the class/method throught out your program and you don't what to create a instance every time you need to use that method.
For ex
public class StaticExample {
public static void reusable() {
//code here
}
}
It means you can use it like this
StaticExample.reusable();
and you don't have to create an instance like this
StaticExample staticExample = new StaticExample();
staticExample.reuseable();
I hope this help you decide whether to use static or not.

Java passing arrays into object issue

In java, how do you pass an array into a class. When ever I do I get a "Can not refrence a non-static variable in a static context". the array has 10 positions. I declared the array as.
edit: is this a clearer example? I should also make note that my teacher completely ignored what is static, and how it is used, claiming it isnt important for the programmer to understand.
edit 2: I managed to get it to work by taking
sorter sort = new sorter();
and turned it into
static sorter sort = new sorter();
what exactly did this do to my program, is this considred a bad fix?
main
public class example {
public static void main(String[] args) {
int[] test = new int[10];
sorter sort = new sorter();
sort.GetArray(test);
}
}
class
public class sorter {
int[] InputAR = new int[10];
public sorter
{
}
public void GetArray(int[] a)
{
}
}
You didn't put enough code, put my guess is :
You declared a non-static field (like int[] test = new int[10] instead of static int ...)
the sort.getArray is in the main or in another static method.
This is not possible, because non static fields need a concrete object to exist.
Its because you are calling sort.GetArray(test) in some static method. You need to make your array variable static so as to access it.
Just read this article and you will understand the issue with your code.
"Can not refrence a non-static varible in a static context"
This error of yours has nothing to do with passing arrays or something.Somewhere in your code,or may be inside public void GetArray(int[] a) you a refering a static member but, with a non-static context.
Make that variable non-static, or the method static, or vice-versa.
Refer This Link for more info.

Categories