Calling methods in other files
I am taking a beginning java class based in a unix environment. I have to create three .java files. One that prints out a simple line of text, one to call the method that prints the line of text and another file that contains the Main that calls the 2nd file. I have tried this a number of different ways to no avail so I am hoping someone can point me in the right direction.
Thanks in advance and sorry if the above explanation is hard to understand.
Re: Calling methods in other files
Lesson: A Closer Look at the "Hello World!" Application (The Java™ Tutorials > Getting Started)
Start with that. Write two very similar files with slightly different names. "HelloWorldApp.java" and "HelloWorldSecond.java" would be okay. Debug them both and run them both from the command line. They both have main methods. Make sure they print slightly different messages. Now change the System.out.println in the second to read something like:
Code java:
/* invoke main with a zero-length array */
HelloWorldApp.main(new String[0]);
Compile and run the second program again. Now you should see the first program's message. The second program has called the first program's "main(String[])" method. You can extend this to three Java files easily. The next step would be to make a nicer method than "main(String[])" to do the message printing. Get coding!
Re: Calling methods in other files
I tried that and It works but I the two other files that I am calling cannot have main methods. Can I use something like Public void init() somehow in place of the main?
Re: Calling methods in other files
This is the code he gave us to follow as an example. Its for a random character generator but I can figure out how to use it simply for strings
public class RandomCharacter {
public static char getRandomCharacter(char ch1, char ch2) {
return (char)(ch1 + Math.random()*(ch2-ch1+1));
}}
The class with the main
public class TestLowerRandomCharacter{
public class static void main(String args[]) {
char ch = RandomCharacter.getRandomLowerCaseLetter();
System.out.Println(ch);
I cut some of the code out in the main class because im not going to use it anyway.
Hope this will help you help me haha
Thanks again
Re: Calling methods in other files
Quote:
two other files that I am calling cannot have main methods.
There are no restrictions on what name you use for methods in a java class. Any and all classes can have a method named: main.
Quote:
how to use it simply for strings
What do you want the method to do?