Can't correct my java program - java

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.

Related

Determining static method with a global LinkedList variable

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

Does the final keyword store variables inside methods like static?

Newbie to Java here. I'm in the process of porting my iPhone app to Android. From what I've read, the final keyword is pretty much equivalent to static. But does it work the same inside a method?
For example in Objective-C inside a method... static Class aClass = [[aClass alloc] init]; wouldn't be reallocated again and it wouldn't be disposed at the end of the method.
Would something in Java inside a method like... final Class aClass = new aClass(); act the same?
No. Block-local variables go out of scope when the block is exited and are logically (and usually physically) allocated on the stack.
Java isn't really like Objective C in that respect, and final is more akin to const because it indicates a reference may not be altered. In your example, when the block ends the final variable will be eligible for garbage-collection as it is no longer reachable. I think you want a field variable something like
static final aClass aField = new aClass();
Note that Java class names start with a capital letter by convention...
static final MyClass aField = new MyClass();
You are confusing the meaning of Final and Static.
Final means that the value of the variable cannot be changed after its value is initially declared.
Static means a variable can be accessed and changed without needing to instantiate a class beforehand.
Perhaps the following bit of code will make this more clear.
public class SF1 {
static int x;
final int y = 3;
static final int z = 5;
public static void main(String[] args) {
x = 1;
// works fine
SF1 classInstance = new SF1();
classInstance.y = 4;
// will give an error: "The final field main.y cannot be assigned"
z = 6;
// will give an error: "The final field main.z cannot be assigned"
reassignIntValue();
// x now equals 25, even if called from the main method
System.out.println(x);
}
public static void reassignIntValue() {
x = 25;
}
}
You have to declare your variable in class scope so you can able to access it outside of your method.
class ABC{
int a;
public void method(){
a = 10; // initialize your variable or do any operation you want.
}
public static void main(String args[]){
ABC abc = new ABC();
System.out.println(abc.a) // it will print a result
}
}

How do i solve this non-static and static variables accessing through methods for once and for all?

I have always had problems with accessing private varibles in a class through a method to another class, for instance now i have this problem :
i have this variable in say class Hello1 :
private Item[][] bankTabs;
and i want to access it through another class say hello2, so i made a public method in Hello1 that is this :
public int amountOfItemInBank(int id) {
int amountInBank = 0;
for(int i = 0; i < bankTabs.length; i++) {
for(int i2 = 0; i2 < bankTabs[i].length; i2++) {
if (bankTabs[i][i2].getId() == id)
amountInBank = bankTabs[i][i2].getAmount();
}
}
return amountInBank;
}
but when i want to access it through Hello2, it tells me the method is not static, and when i make it static, the variable bankTabs in amountOfItemInBank do not work and i get a lot of errors.
so when i go to Hello2 class, and i try to call this method like this :
Hello1.amountOfItemInBank(50);
how can i solve this?
Either make an object of Hello1 class and then access the method
Hello1 obj = new Hello1();
int returnValue = obj.amountOfItemInBank(50);
or declare both the variable bankTabs and method amountOfItemInBank as static in Hello1 class and use Hello1.amountOfItemInBank(50); as you did earlier.
Also, read more here Understanding Class Members to clear your understanding and then you can solve the problem for once and for all.
Static METHODS can be called on class, and not object, like
Hello1.amountOfItemInBank(50);
To call a non-static method, you need an object of a class:
Hello1 hello = new Hello1();
hello.amountOfItemInBank(50);
The method doesn't have to be static to make use of a static field in such way. Declaring a field as static lets you use its value (if it's public) without making object of a class:
Item[][] items = Hello1.bankTabs;
or by a method call (if it's private):
Hello1 hello = new Hello1();
Item[][] items = hello.getBankTabs();
// in your class
private static Item[][] bankTabs;
public Item[][] getBankTabs() {
return bankTabs;
}
If you do not need to access the field without instantiating the class, you probably do not want to make that variable static.

Can a method be called by an object inside of the same class?

What I'm trying to understand is why I'm receiving an error when I try to call a method by an object whilst residing in the same class.
My syntax looks correct. I understand the local variables inside of the method are uninitialized, and wanted to see if the compiler would be able to pick this up.
My issue however is, I receive a stupid error from the compiler, when I try to invoke the method on an object of the same class, within the class, as such.
class Wool {
public static void main (String [] args) {
int add() {
int x;
int a = x + 3;
return a;
}
Wool w = new Wool ();
System.out.print("something here " + w.add());
} // end main
} // end class
There error that I receive from the compiler is:
c Wool.java
Wool.java:5: ';' expected
int add() {
^
I can do the above fine, if the object of type Wool is instantiated in another class, and the object has no issue in invoking the method, to show me the compilation error that the local variables need a value in that method.
I just don't understand why I can't do it in one class. And if it is possible, please could you educate me.
Help would be immensely grateful.
Thank you.
You can't define a method inside another one. You must declare the add method outside of the main method.
Change your code to
class Wool {
int add() {
int x = 0; // give a value to avoid another error
int a = x + 3;
return a;
}
public static void main (String [] args) {
Wool w = new Wool ();
System.out.print("something here " + w.add());
} // end main
} // end class
You are declaring a method inside main(). You can not do that.
Methods must be declared inside classes, not inside other methods.
Because add() is not defined as a class method, but you define it as "local" method within main, which is not allowed in java. You must change it to
class Woo{
void add(){
....
}
public static void main(String[] args){
new Woo().add();
...
}
}
You have a method directly inside a method:
main(){
add() {
}
}
that's illegal in java.
Put your method add in the body of your class but not in the body of your method main. Or better : leave Java alone :)
You can't declare a method inside a method.
Try this:
public static void main (String[] arts) {
//
}
int add() {
//
}

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