Reputation: 1260
I have a java program define like this :
public class MyClass{
public String getPathBetween(String path,String folderName,String extension){..}
public static void main(String[] args) throws Exception{...}
}
After compiling the program using following command :
$ javac MyClass.java
I can run the main method like this :
$ java MyClass
But how can I run the method getPathBetween ?
I tried this , but with no avail :
$ java MyClass.getPathBetween("some text", "some","text")
Upvotes: 1
Views: 58
Reputation: 339303
As noted in the Answer by ndc85430, the method names main
is always the entry point for a Java app executed in the command line (console).
As noted in the Answer by Mickey, the user can pass arguments while calling your Java app on the command-line.
See this tutorial provided by Oracle.
You also have the ability to interact with the user on the command line. Use System.out
to print instructions and menu options to be read by the user. Use a Scanner
object to receive and parse input typed by the user on the command line.
See this tutorial by Oracle, I/O from the Command Line.
Search Stack Overflow to find many examples. This approach is frequently used in tutorials and textbooks for beginning Java students.
You might be interested in the REPL bundled with Java, JShell.
With JShell, you can type Java code to be executed immediately. You can instantiate an object if your class. And you can invoke methods on that object.
Upvotes: 1
Reputation: 7716
//You can create an instance of MyClass in your main() method
// and then call getPathBetween():
public class MyClass{
public String getPathBetween(String path, String folderName, String extension){..}
public static void main(String[] args) throws Exception{
MyClass myClassInstance = new MyClass();
String path = "/some/path/value";
String folder = "my-test-folder";
String extension = "xyz";
String pathBetween = myClassInstance.getPathBetween(path, folder, extension);
System.out.println("pathBetween=" + pathBetween);
}
}
Or if you want to be able to pass values into getPathBetween()
from the command line, you could change the code to:
public class MyClass{
public String getPathBetween(String path, String folderName, String extension){..}
public static void main(String[] args) throws Exception{
MyClass myClassInstance = new MyClass();
String path = args[0];
String folder = args[1];
String extension = args[2];
String pathBetween = myClassInstance.getPathBetween(path, folder, extension);
System.out.println("pathBetween=" + pathBetween);
}
}
And then run it like so:
java MyClass "some text" "some" "text"
Upvotes: 1
Reputation: 1743
You need to call the method from main
. The entry point of a program is always main
.
Upvotes: 1