Reputation: 73
I have Googled this several times, but as a newb, I am completely unclear as to how I would pass a parameter, which is an int
variable, from one of my methods, into my main method. I have a method, getInput()
, which returns an int
, but I can't pass it to main. My constructor and main method are as follows
public Mainmenu9(int choice){
//constructor
System.out.println("Choice is :" + choice);
}
public static void main(String args[]){
Mainmenu9 team = new Mainmenu9(choice);
System.out.println("team :" + team.choice);
getInput();
} // end main method
The reason I want to pass this int variable into the main method, is because I have read about serialization and I know that in order to write to a file, I need to convert int variable to an object. My code only works, if I declare the int as a static class variable, but then I lose the returned value, the int is always 0 , as there is no value and it has not been initialised.
I'm not looking for someone to do it for me, just a pointer in the right direction.
Upvotes: 1
Views: 4692
Reputation: 121619
"main()" is the "start" of your program.
The only thing that calls in to "main()" is you (by way of the operating system), when you start your program.
For example, this illustrates "passing arguments from the command line":
public class MyClass {
public static void main (String[] args) {
System.out.println ("#/args=" + args.length);
for (String s:args) {
System.out.println ("next arg=" + s);
}
}
}
java MyClass <-- No args
java MyClass a b c <-- Will pass the three arguments "a", "b" then "c"
In the second example, you can pass "a", "b" and/or "c" to any of the objects your "main()" might instantiate. For example, "a" might be the "choice" in your "Menu" class.
Upvotes: 1
Reputation: 16636
The only scenario where you would call the main
method from inside the application is when you're unit testing
it.
For any other purposes, use it just to receive parameters from the command line
.
Upvotes: 2
Reputation: 2466
You're going about this all wrong. The main method is used to initiate action (ie methods, constructors etc). The goal is to use the main method as an entry point for your program
If you want to pass a parameter into your main method this needs to be done with command line args.
Upvotes: 3