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.
Related
I'm having a really hard time deciding when to make my methods static or not. I was told to make a global LinkedList variable:
public static LinkedList list = new LinkedList();
Now, I wrote a method called read() to read in words from a text file. Then I wrote another method preprocessWord(word) to check if these words begin with a constant to change them to lower-case. If they have these conditions, then I add them to the LinkedList list:
public void read(){
....
while((nextLine = inFile.readLine())!= null){
tokens = nextLine.trim().split("\\s+");
for(int i = 0; i < tokens.length; i++){
word = tokens[i];
word = preprocessWord(word);
list.append(word);}
}
}
...
}//read
However, when I try to call read() from the main method;
public static void main(String[] args) {
read();
System.out.println(list);
}//main
The error is I cannot make a static reference to a non-static method read(), so I tried to change my methods read() and preprocessedWord() to static methods, but then words aren't updated in preprocessedWord() like they are suppose to. I really don't get where to use static and to where not, could someone please explain where I'm going wrong in my thinking?
in laymen's terms, when you define a method non-static, it can only be invoked on an instance of this class. In your case however you would need to run something like this
public static void main(String[] args) {
new YourClassName().read();
System.out.println(list);
}
Doing so however, would mean that in your read method, you would have to access the static list as
YourClassName.list.append(word)
The other approach would be to make read static as well, so in this case your method signature should be
public static void read()
Cuz your read method is not static. Dont use satic field unless you need to eg. for sharing reference between all objects of the same class. Make your list non-static or even local and pass as argument to subsequent methods calls
I consider myself an intermediate Java programmer having been at it for a year and a half and having some experience in other languages. However I have run into an issue that I feel I need an experts help on.
As I understand it arrays when created by java exist somewhat outside of where they were created i.e. if you create an array called s in one class and another called s in a second class then try to use both those classes as part of a program you will run into problems with them overwriting each other.
However this brings me to an interesting dilemma. What if one wanted to create a unique array on-demand for an infinite number of sets of user input. i.e. is it possible to have the user enter a string value for use as the array name or have a generic value that then gets a number or letter appended to it. This is more a theoretical issue (there being other ways to accomplish the same thing) but any insight would be greatly appreciated.
i.e. is it possible to have the user enter a string value for use as
the array name or have a generic value that then gets a number or
letter appended to it.
The user should not need to care about your array names. The name of an array should neither be visible to the user, nor should it affect your application in any way.
If you want to allow the user to create collections of elements that he can store under a FriendlyName you could use a (Hash)map for that:
Map<String, Integer[]> userDefinedArrays = new HashMap<>();
userDefinedArrays.put("NameTheUserSelectsForThisArray", new Integer[]{1,2,3});
The "Key" of this map will be the FriendlyName provided by the user - he still does not know, that the actual map is called userDefinedArrays - or even someMapThatHoldsSomeThingsTheUserWantToUse.
The name of a actual variable needs to be set during designtime and is fixed (at least in java)
if you create an array called s in one class and another called s in a second class then try to use both those classes as part of a program you will run into problems with them overwriting each other.
No! Each Variable declared exists inside it's own scope! You can change the value of an array inside it's scope, and also reuse the same name inside different scopes - it doesn't matter. If you try to redeclare a variable already existing withing the current scope your compiler will warn you! - you simple can not do that.
Example:
class MyApplication{
public static void Main(String[] args){
Integer[] arr1;
Integer[] arr1; //Compiler error!
}
}
but:
class MyApplication{
public static void Main(String[] args){
Integer[] arr1;
Integer[] arr2;
}
}
or
class MyApplication{
public static void Main(String[] args){
foo();
bar();
}
public static void foo(){
Integer[] arr1;
}
public static void bar(){
Integer[] arr1;
}
}
is fine. arr1 just exists within the scope of either foo() or bar().
As I understand it arrays when created by java exist somewhat outside of where they were created i.e. if you create an array called s in one class and another called s in a second class then try to use both those classes as part of a program you will run into problems with them overwriting each other.
I think maybe you are misunderstanding. This will not happen unless you do it intentionally like yshavit points out in your comments. A member of a class named S in the class Cat, will not point to a member named S in the Dog class. You would have to go out of your way to do this.
In short, this will not happen by accident most of the time if you are instantiating your classes without passing references between them when you do.
What if one wanted to create a unique array on-demand for an infinite number of sets of user input.
You may want to use an ArrayList
ArrayList<String[]> myList = new ArrayList<String[]>();
Or a hashmap
Map<Integer,String[]> myMap = new HashMap<Integer,String[]>();
Which one you use depends on what you are using it for. If you need faster access to arbitrary elements use a map. If you plan to access them iteratively, an ArrayList will work fine.
is it possible to have the user enter a string value for use as the array name or have a generic value that then gets a number or letter appended to it. This is more a theoretical issue (there being other ways to accomplish the same thing) but any insight would be greatly appreciated.
In this case you want to use the hashmap solution, You can choose the key type of a map in java quite easily.
You will want to read this
http://docs.oracle.com/javase/6/docs/api/java/util/Map.html
or this, to get started.
http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html
Two different class you're talking about is ClassOne & ClassTwo in my example. As you told, there is some kind of conflict while keeping the field name same. I've used arr for both classes. The reason to make MyArray super class is just code reuse. Why I used abstract MyArray class & why I used public static field isn't our matter of discussion. In TestApp, I've used arr of both classes ClassOne & ClassTwo without any problem.is it possible to have the user enter a string value for use as the array nameIMHO it may be possible using Reflection API or Dynamically Typed Language can do it. I'm not much sure about that.
class ClassOne extends MyArray {
public static int[] arr = new int[5];
}
class ClassTwo extends MyArray {
public static int[] arr = new int[5];
}
abstract class MyArray {
public static void setValue(int arr[], int index, int value) {
arr[index] = value;
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
public class TestApp {
public static void main(String[] args) {
ClassOne.setValue(ClassOne.arr, 1, 30);
ClassTwo.setValue(ClassTwo.arr, 1, 50);
ClassOne.printArray(ClassOne.arr);
ClassOne.printArray(ClassTwo.arr);
ClassTwo.printArray(ClassOne.arr);
ClassTwo.printArray(ClassTwo.arr);
}
}
I am trying to get getIntArrayString to accept parameters given to it, unlike abc.getAverage which uses the field testArray.
edit: Forgot to ask the question.
how would I be able to send parameters such as test1 to getIntArrayString()?
private int testArray;
public static void main(String[] args)
{
int[] testArray = new int[]{2,4,6,8,9};
ArrayHW abc = new ArrayHW(testArray);
System.out.printf(abc.getAverage());
int[] test1= new int[]{3,4,5,6,7};
System.out.printf("Array Values: %s\n",ahw.getIntArrayString());
int[] test1= new int[]{3,4,5,6,7}
System.out.printf("Array Values: %s\n",ahw.getIntArrayString());
}
I'm assuming you have a method named getIntArrayString inside another class. If you want to send the values of test1, the method getIntArrayString must have a parameter of test1's datatype. For example,
public int getIntArrayString(int [] x)
{
}
You should review your knowledge of methods.
Having two variables called testArray may seem a little confusing, but it's not syntactiacally wrong. However, it's less confusing to read your code if you don't, and even better if you remove any unused variables.
You are not posting any error messages, but I suppose you can't compile because you haven't declared any variable "ahw", and ahw.getIntArrayString() produces a compiler error.
In general, in order to be able to send a parameter of type int[] to a method it would be declared like this:
public String getIntArrayString(int[] intArray) { ... }
And you would call it like this
System.out.println(x.getIntArrayList(test1));
where test1 is an int array as declared in your own code.
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.
I just started learning java and I'm working on a program. I'm getting an error here:
locationsOfCells = simpleDotCom.getLocationCells();
but I'm not sure what the error is. Eclipse say
Cannot make a static reference to the non-static method
getLocationCells() from the type simpleDotCom
Can someone help me with this? What am I doing wrong?
public class simpleDotCom {
int[] locationsCells;
void setLocationCells(int[] loc){
//Setting the array
locationsCells = new int[3];
locationsCells[0]= 3;
locationsCells[1]= 4;
locationsCells[2]= 5;
}
public int[] getLocationCells(){
return locationsCells;
}
}
public class simpleDotComGame {
public static void main(String[] args) {
printBoard();
}
private static void printBoard(){
simpleDotCom theBoard = new simpleDotCom();
int[] locationsOfCells;
locationsOfCells = new int[3];
locationsOfCells = theBoard.getLocationCells();
for(int i = 0; i<3; i++){
System.out.println(locationsOfCells[i]);
}
}
}
The problem is you are calling the getLocationCells() method as if it was a static method when in fact it is an instance method.
You need to first create an object from your class like this:
simpleDotCom myObject = new simpleDotCom();
and then call the method on it:
locationsOfCells = myObject.getLocationCells();
Incidentally, there is a widely followed naming convention in the Java world, where class names always start with a capital letter - you should rename your class to SimpleDotCom to avoid confusion.
you are trying to reference a non static method from the main method. That is not permitted in java. You can try making that simpleDotCom Class as static, so that u can have access to the methods of that class.
simpleDotCom obj = new simpleDotCom();
locationsOfCells = obj.getLocationCells();
And also your class name should start with a capital letter
You are attempting getLocationCells in a static way. You need to create an instance of simpleDotCom first:
simpleDotCom mySimpleDotCom = new simpleDotCom();
locationsOfCells = mySimpleDotCom.getLocationCells();
BTW class names always start with a capital letter. This would help remove the confusion of accessing the method as a member method.
Update:
To access from your updated static method, you would need to declare theBoard as a static variable also:
static simpleDotCom theBoard = new simpleDotCom();
Either make simpleDotCom's fields and methods static, too, or create an instance of simpleDotCom and access the instance's method.
You are trying to access a normal non static method from a static context, it does not work.
You can either remove the static word from the routine where you try to access the: getLocationCells() from, or make getLocationCells() static by adding the static word in its declaration.
Your code have some more errors.
The non static method couldn't call up with class name. So try to call the getLocationCells() with object.
simpleDotCom obj=new simpleDotCom();
obj.getLocationCells()
Next u will get the null pointer exception. U try to print the locationsOfCells values before it is initialized. So try call the setLocationCells() method before printing values.
Ur method definition void setLocationCells(int[] loc). Here u having the parameter loc but u didn't use any where in the method block. So please aware of handling method parameter.