Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: Call static method from another class - SPMF library

  1. #1
    Junior Member
    Join Date
    Jan 2019
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Call static method from another class - SPMF library

    Hi

    I am trying to adapt some code from the SPMF library, specifically one package, but I am running into problems. There are several examples that the library provide that either print to screen or to outfile. I am attempting to alter these to return a list. The method that I wish to output prints to the screen okay, but when I try to output the list it fails. I think I am messing up with the method types in the second class method, 'MainTestCPTPlus2'.

    Specifically, i have a method in a second class 'MainTestCPTPlus2' that calls a method from another class 'SequenceStatsGenerator2'

    There are no visible errors when developing the code in Eclipse, but when I call it in R I get the following error that the method is not recognised suggesting that the Java code is incorrect .

    Error in .jcall("RJavaTools", "Ljava/lang/Object;", "invokeMethod", cl, : java.lang.NoSuchMethodException: MainTestCPTPlus2.getStats()

    I'm sorry, I have been unable to add the relevant code to the question as it must have some forbidden words, hence "Post denied", but I have added the code to github: github(dot)com/david-p1/test. The readme has the original question and code, as well as the full java package.

    thanks, david

    (ps I did strip out all webpage links and text just leaving the code before I tried to submit the question but it was denied)

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Call static method from another class - SPMF library

    Try to post the code again that shows the definition of the static method and the code that calls it. I've seen other beginners that have been able to post code.
    Be sure to wrap the code in code tags
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Jan 2019
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Call static method from another class - SPMF library

    Hi Norm,

    thanks for the response; code posted below -- apologies, I don't know what I did yesterday to get it denied!

    I'd be grateful for any pointers,
    david

    ---- EDIT ------

    I am trying to get the method 'getStats' from class 'MainTestCPTPlus2' to output a list; this method is dependent on the method 'Stats2' from the class 'SequenceStatsGenerator2'.


    -----------------

    The is the first class and method:

    import ipredict.database.SequenceDatabase;
    import ipredict.database.Sequence;
    import ipredict.database.Item;
     
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.*;
     
    public class SequenceStatsGenerator2 {
     
     
    	/**
    	* This method generates statistics for a sequence database (a file)
    	* @param path the path to the file
    	* @throws IOException  exception if there is a problem while reading the file.
    	*/
    	public static List<Object> Stats2(SequenceDatabase database) {
     
     
    		// we initialize some variables that we will use to generate the statistics
    		java.util.Set<Integer> items = new java.util.HashSet<Integer>();  // the set of all items
    		List<Integer> sizes = new ArrayList<Integer>(); // the lengths of each sequence
     
    		// Loop on sequences from the database
    		for (Sequence sequence : database.getSequences()) {
    			// we add the size of this sequence to the list of sizes
    			sizes.add(sequence.size());
     
    			// this map is used to calculate the number of times that each item
    			// appear in this sequence.
    			// the key is an item
    			// the value is the number of occurences of the item until now for this sequence
    			HashMap<Integer, Integer> mapIntegers = new HashMap<Integer, Integer>();
     
    			// Loop on itemsets from this sequence
    			for (Item item : sequence.getItems()) {
    			// we add the size of this itemset to the list of itemset sizes
    				// If the item is not in the map already, we set count to 0
    				Integer count = mapIntegers.get(item.val);
    				if (count == null) {
    					count = 0;
    				}
    				// otherwise we set the count to count +1
    				count = count + 1;
    				mapIntegers.put(item.val, count);
    				// finally, we add the item to the set of items
    				items.add(item.val);
     
    			}
    		}
     
    		// return
    		int nodi = items.size() ;
    		double ips = calculateMean(sizes);		
     
    		return Arrays.asList(nodi, ips);
     
    		}
     
    	/**
    	 * This method calculate the mean of a list of integers
    	 * @param list the list of integers
    	 * @return the mean 
    	 */
    	private static double calculateMean(List<Integer> list) {
    		double sum = 0;
    		for (Integer val : list) {
    			sum += val;
    		}
    		return sum / list.size();
    	}
    }


    And this is the second class which has a method 'getStats'; this calls the method 'Stats2' from the above class 'SequenceStatsGenerator2' in the line
    List<Object> id = SequenceStatsGenerator2.Stats2(trainingSet)

    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.net.URL;
    import ipredict.database.SequenceDatabase;
    import java.util.*;
     
     
    public class MainTestCPTPlus2 {
     
    // This method reads in a text file, and converts it to a format that can be used by SPMF
    // Using this data, some summary statistics are grabbed using the method SequenceStatsGenerator2.Stats2
    // The function returns the calculated summary stats
    public static List<Object> getStats(String[] args) throws IOException{
     
    	// Load the set of training sequences
    	String inputPath = fileToPath("contextCPT.txt");  
    	SequenceDatabase trainingSet = new SequenceDatabase();
    	trainingSet.loadFileSPMFFormat(inputPath, Integer.MAX_VALUE, 0, Integer.MAX_VALUE);
     
    	List<Object> id = SequenceStatsGenerator2.Stats2(trainingSet);
    	return id ;
     
    }
     
    public static String fileToPath(String filename) throws UnsupportedEncodingException{
    	URL url = MainTestCPTPlus2.class.getResource(filename);
    	 return java.net.URLDecoder.decode(url.getPath(),"UTF-8");
    }	
     
    public static void main(String[] args) {
     
    }
    }


    If I change the second method to print to screen, it outputs correctly, suggesting it is how I have specified the method 'getStats' in the previous attempt above.


    public static void main(String [] args) throws IOException{		
    	// Load the set of training sequences
    	String inputPath = fileToPath("contextCPT.txt");  
    	SequenceDatabase trainingSet = new SequenceDatabase();
    	trainingSet.loadFileSPMFFormat(inputPath, Integer.MAX_VALUE, 0, Integer.MAX_VALUE);
     
    	List<Object> id = SequenceStatsGenerator2.Stats2(trainingSet);
    	System.out.println(id);
    }
    Last edited by davi-d; January 12th, 2019 at 04:05 PM.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Call static method from another class - SPMF library

    Why are there two main methods?
    Why is the statement in the main method in MainTestCPTPlus2 that calls a static method commented out?

    this is the secnd which calls the first one:
    Could you be more specific? The second what? What is its name?
    Where does it do the call?
    What is the name of the method that is called?

      new MainTestCPTPlus2().getStats(args);
    There is no need to create an instance of a class to call a static method.
      MainTestCPTPlus2.getStats(args);    // call static method in MainTestCPTPlus2 class

    Also the code ignores what is returned by the getStats method.

    Here is an example of calling a static method and saving what is returned from your code:
    	List<Object> id = SequenceStatsGenerator2.Stats2(trainingSet);
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Jan 2019
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Call static method from another class - SPMF library

    Hi Norm

    Thanks again; I have edited the above post.

    Re your questions:

    Why are there two main methods?
    When testing the code, I used the second main method (void) to output to the screen - which it does as expected. I do not include both main functions when compiling the code. I am trying to get the method 'getStats' in the MainTestCPTPlus2 class to run.

    Why is the statement in the main method in MainTestCPTPlus2 that calls a static method commented out?
    This was a residual from things I was trying; it gave errors when trying to compile. I have removed the line.

    Also the code ignores what is returned by the getStats method.

    Here is an example of calling a static method and saving what is returned from your code:

    List<Object> id = SequenceStatsGenerator2.Stats2(trainingSet);
    I'm sorry, I don't understand and this may be the crux of the problem; I did assign the results of 'SequenceStatsGenerator2.Stats2(trainingSet);' to the `id` object as you show, and tried to return it.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Call static method from another class - SPMF library

    I don't understand
    What is not understood?
    How to call a static method?
     TheClassName.theStaticMethodName();   // call a static method

    How to save what a method returns?
     theValue = theMethod();   // save what the method returns

    The posted code has one statement that does both of those things:
    	List<Object> id = SequenceStatsGenerator2.Stats2(trainingSet);  // call static method and save returned value

    tried to return it.
    Where is the returned value saved and used for anything?

    it gave errors
    Copy the full text of any error messages and paste them here.


    What is the posted code supposed to do? I don't see any comments in your code that explains what it is trying to do.
    The SequenceStatsGenerator2 class has useful comments describing what it is doing.
    If you don't understand my answer, don't ignore it, ask a question.

  7. The Following User Says Thank You to Norm For This Useful Post:

    davi-d (January 12th, 2019)

  8. #7
    Junior Member
    Join Date
    Jan 2019
    Posts
    4
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Call static method from another class - SPMF library

    okay, thank you for your time, and help.

    so it seems as if there is not any obvious error in the code

    What I am doing: I am trying to develop code in Java but call it in R -- it is the call in R that would execute the method 'MainTestCPTPlus2.getStats()`and would be able to grab the return value from 'getStats()'.

    However, from R I was getting the error given in the original post

    Error in .jcall("RJavaTools", "Ljava/lang/Object;", "invokeMethod", cl, :
    java.lang.NoSuchMethodException: MainTestCPTPlus2.getStats()
    I had assumed this was due to errors in my Java code but perhaps it is on the r side.

    Thanks again.

  9. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Call static method from another class - SPMF library

    Sorry, I know nothing about "r side".

    In normal java programs, the main method in a class is executed when that class is executed by the java command.
    For example:
    >java MainTestCPTPlus2
    would cause execution to start in the main method in the MainTestCPTPlus2 class.

    Can you post the actual code that gets the error? The call to the static method was commented out in the posted code.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. How to call a non static method from a static method
    By anthony.aa86 in forum Object Oriented Programming
    Replies: 2
    Last Post: December 26th, 2013, 02:29 PM
  2. Cannot call method because it is non-static
    By thegorila78 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: November 7th, 2013, 01:19 PM
  3. How to call a static method within a static method in the same class?
    By EDale in forum What's Wrong With My Code?
    Replies: 4
    Last Post: May 10th, 2013, 04:13 AM
  4. update static field and call method within the class?
    By GeneralPihota in forum Object Oriented Programming
    Replies: 7
    Last Post: February 6th, 2012, 09:20 PM
  5. Call method(s) within the same class
    By mwr76 in forum Object Oriented Programming
    Replies: 8
    Last Post: September 26th, 2011, 12:58 AM

Tags for this Thread