ELSheepO
ELSheepO

Reputation: 305

Call Method from Main Java

I'm trying to call a method, WriteToFile, from The main method. Here is what I have so far:

public void main(String [ ] args)
{
    String fileLoc = Environment.getExternalStorageDirectory() + File.separator + "AccelData.txt";

    File AccelData = new File(fileLoc);

    AccelData.WriteToFile(fileLoc, AccelData);
}

And the WriteToFile method is:

public void WriteToFile(String fileLoc, File AccelData){
    //code in here
}

I get a red line under the AccelData.WriteToFileline, which just says I should add a cast, which doesn't fix it.

Thanks for your help.

Upvotes: 0

Views: 1576

Answers (3)

Juvanis
Juvanis

Reputation: 25950

You cannot apply WriteToFile() method to java.io.File instances, becuase it's not defined in standard Java File class.

One alternative way you can apply to your code is declaring your method as static:

public static void WriteToFile(String fileLoc, File AccelData){
    //code in here
}

And in the main method just call it with its name:

WriteToFile(fileLoc, AccelData);

Second way could be creating an instance of the class which encapsulates WriteToFile() method, and then invoking that method on your instance again in main method:

YourClass obj = new YourClass();
obj.WriteToFile(fileLoc, AccelData);

Upvotes: 1

Sumit Singh
Sumit Singh

Reputation: 15886

First i would like to say that signature of your main method is not correct, it's.:

public static void main(String [ ] args)
 {
   // do somthing 
 }

Go to this link A Closer Look at the "Hello World!" Application

And second you are calling a method with its class name then that method should be static like following

public static void WriteToFile(String fileLoc, File AccelData){
 //code in here
}

Or you have to call that method with its class object.

public static void main(String [ ] args)
 {
   String fileLoc = Environment.getExternalStorageDirectory() + File.separator + "AccelData.txt";

   File AccelData = new File(fileLoc);

   ClassName className= new ClassName();
   className.WriteToFile(fileLoc, AccelData);
}

Upvotes: 2

Tobias Ritzau
Tobias Ritzau

Reputation: 3327

If you define your method in your own class you should remove the AccelData. part:

public static void WriteToFile(String fileLoc, File accelData) {
    //code in here
}

public static void main(String [ ] args)
{
    String fileLoc = Environment.getExternalStorageDirectory() + File.separator + "AccelData.txt";

    File accelData = new File(fileLoc);

    WriteToFile(fileLoc, accelData); 
}

You should not name variables with an initial capital. That is confusing. The same goes for methods. And you do need ta make the methods static.

Upvotes: 0

Related Questions