Question:
Java question - the main function and the 'static' identifier?
?
2011-05-09 17:37:37 UTC
Hello there. I am doing a short java project for school, and I'm pretty new to it. We didn't really have anybody teach us java-- my teacher just wanted us to do whatever we wanted.

Anyways. So I am making a java app that pitches you into a game of Go Fish against some AI. I already know how to do all that at least, but one thing gets in my way repeatedly.

When I try to call a non-static function from the main function, it gives me an error. So I have to make all my other functions static. However, this means I cannot declare any variables outside of functions, and for boolean arrays at least that isn't possible.

I found that creating an entirely new boolean array as a function itself worked, but that looks very sloppy! Does anyone have any other solutions?
Three answers:
question asker
2011-05-09 18:01:06 UTC
You can create an instance of the class inside the main method. And for accessing variables outside of function just use member variables. Like this:



public class JavaTest {



int x, y;



public static void main(String[] args) {

JavaTest JT = new JavaTest(5, 8);

JT.displayCoords();

}



public JavaTest(int xIn, int yIn) {

this.x = xIn;

this.y = yIn;

}



public void displayCoords() {

System.out.println("x: " + x + ", y: " + y);

}

}
Damien Bell
2011-05-09 17:44:44 UTC
Yep, you need to better understand set and get methods in java.



Assume that you have the following code outside main in a public, non-static location.



public class number{

private int num;



public int getNum(){

return num;

} // End get Num



public void setNum(int x){

x = num;

}



All you'd need to do after that is something like this:

int x=0; // or whatever

Number number = new Number();

number.setNum(x);



x=Number.getNum(); // assuming your other class is called Number
Jerry
2011-05-09 18:26:45 UTC
You don't want all your methods to be static. Just use the static main method to create an instance of the class, and work that way:



public class GoFish {

public static void main(String args[]) {

GoFish game = new GoFish();

game.play();

}



public void play() {

List cards = shuffle();

//etc...

}



public List shuffle() {

//blah blah...

}



//etc...

}


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...