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 14 of 14

Thread: Trouble calling static methods from another class

  1. #1
    Member
    Join Date
    Dec 2018
    Location
    Wisconsin
    Posts
    54
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Default Trouble calling static methods from another class

    I'm having problems calling my StaticMethodExample class in the main method of my Test class. I'm surprised, because both of those classes are in the same package.

    Here is the StaticMethodExample class that defines the methods:
    package sam;
    import java.util.Scanner;
     
    public class StaticMethodExample {
     
    	public static void pringMessage(){
    		System.out.println("Hello. I'm from a static void method.");
    	}
     
    	public static int multiplyInts(int x, int y){
    		Scanner input = new Scanner(System.in);
    		System.out.print("Enter an int value for x: ");
    		x = input.nextInt();
    		System.out.println();
    		System.out.print("Enter an int value for y: ");
    		y = input.nextInt();
    		System.out.println();
    		int result = x * y;
    		return result;
    	}
    }

    And here is the Test class, where I'm trying to call them:
    package sam;
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import java.util.Scanner;
     
     
    public class Test {
     
    	public static void main(String[] args){
     
    		StaticMethodExample.printMessage();
    		StaticMethodExample.multiplyInts(x, y);
     
    	}//end of main
    }//end of class Test

    The error on line 11 says, "The method printMessage() is undefined for the type StaticMethodExample".

    The error on line 12 says that neither x or y can be resolved to a variable.


    What is wrong?

  2. #2
    Member MrLowBot's Avatar
    Join Date
    Nov 2018
    Location
    Sweden
    Posts
    130
    Thanks
    0
    Thanked 2 Times in 2 Posts

    Default Re: Trouble calling static methods from another class

    Try to call it but not in that way.
    StaticMethodExample obj = new StaticMethodExample();
    And then
    obj.printMessage();
    obj.multiplyInts(x, y);
    Also x and y need to be an input right? Or just delete them all together...
    Doesn't seem like they do anything.
    Last edited by MrLowBot; January 18th, 2019 at 07:46 AM.
    "Tick, tack"

  3. #3
    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: Trouble calling static methods from another class

    The method printMessage() is undefined for the type StaticMethodExample
    The compiler can not find a static method named: printMessage in the StaticMethodExample class. Check the spelling.

    neither x or y can be resolved to a variable.
    The compiler can not find a definition for x or y where they are used in the code. Make sure they are defined before using them.
    If you don't understand my answer, don't ignore it, ask a question.

  4. #4
    Member
    Join Date
    Dec 2018
    Location
    Wisconsin
    Posts
    54
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Default Re: Trouble calling static methods from another class

    Quote Originally Posted by MrLowBot View Post
    Also x and y need to be an input right? Or just delete them all together...
    Doesn't seem like they do anything.
    Nope. Getting rid of x and y also causes an error, "The method multiplyInts(int, int) in the type StaticMethodExample is not applicable for the arguments ()".

    Quote Originally Posted by Norm View Post
    The compiler can not find a definition for x or y where they are used in the code. Make sure they are defined before using them.
    What do you mean? They're already defined in the multiplyInts function definition in the StaticMethodExample class. They're assigned to user input on lines 25 and 28:
    package randomExperiments;
     
    import java.util.Scanner;
    /*
     
     */
    public class StaticMethodExample {
     
    	private static Scanner sc = new Scanner(System.in);	
    	public static String getString(String prompt) {
    		System.out.print(prompt);
    		String str = sc.nextLine();
    		return str;
    	}
    	//to call this method in another class: String myString = StaticMethodExample.getString("Enter a product code: ");
     
    	public static void printMessage(){
    		System.out.println("Hello. I'm from a static void method.");
    	}
    	//to call this method in another class: StaticMethodExample.printMessage();
     
    	public static int multiplyInts(int x, int y){
    		Scanner input = new Scanner(System.in);
    		System.out.print("Enter an int value for x: ");
    		x = input.nextInt();
    		System.out.println();
    		System.out.print("Enter an int value for y: ");
    		y = input.nextInt();
    		System.out.println();
    		int result = x * y;
    		return result;
    	}
    	//to call this method in another class: StaticMethodExample.multiplyInts(x, y);
    }

    But this isn't the only place that I'm confused about passing arguments/parameters. The book also provided the code from lines 9 to 14. Needless to say, the goal of that function is to provide access to the private sc variable, but I'm completely lost, then, to what the point of the prompt variable is.

    Here is the class that's supposed to call the static methods:
    package randomExperiments;
     
    import java.util.Scanner;
    import java.util.Random;
     
    public class RandomExperiments {
     
    	public static void main(String[] args){		
     
    		String myString = StaticMethodExample.getString("Enter a product code: ");
    		System.out.println(str);
    		StaticMethodExample.printMessage();
    		StaticMethodExample.multiplyInts(x, y);		
    	}
    }
    Line 11 is the only statement directly from the book in this class. But the way the code is, I can't figure out what I'm supposed to with the str argument returned from the getString function.

    I'm also still baffled as to why the x and y arguments passed in on line 14 cannot be resolved to a variable.
    Last edited by SamJava_the_Hut; January 23rd, 2019 at 05:33 AM. Reason: There's another static example from my book that I don't understand.

  5. #5
    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: Trouble calling static methods from another class

    If there are error messages, please copy the full text and paste it here.

    cannot be resolved to a variable.
    The compiler can not find a definition for that variable that is in scope where it is being used.
    If you don't understand my answer, don't ignore it, ask a question.

  6. #6
    Member
    Join Date
    Sep 2018
    Location
    Virginia
    Posts
    284
    My Mood
    Cool
    Thanks
    0
    Thanked 38 Times in 36 Posts

    Default Re: Trouble calling static methods from another class

    That is not the proper way to call a static method. It will work but you should either do an import static or fully qualify it with the class name. An instance of the class is not required.

    Regards,
    Jim

  7. #7
    Member
    Join Date
    Dec 2018
    Location
    Wisconsin
    Posts
    54
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Default Re: Trouble calling static methods from another class

    Quote Originally Posted by jim829 View Post
    It will work but you should either do an import static or fully qualify it with the class name.
    Okay done. randomExperiments.java now looks like this:
    package randomExperiments;
     
    import java.util.Scanner;
    import java.util.Random;
    import static randomExperiments.StaticMethodExample.*;
     
    public class RandomExperiments {
     
    	public static void main(String[] args){		
     
    		String myString = StaticMethodExample.getString("Enter a product code: ");
    		StaticMethodExample.printMessage();
    		StaticMethodExample.multiplyInts(x, y);		
    	}
    }
    But that didn't fix the problem. I still don't know where the program wants me to define the x and y arguments. Like I said in my response to Norm, they're already defined in the multiplyInts function in the StaticMethodExample class:
    public static int multiplyInts(int x, int y){
    		Scanner input = new Scanner(System.in);
    		System.out.print("Enter an int value for x: ");
    		x = input.nextInt();
    		System.out.println();
    		System.out.print("Enter an int value for y: ");
    		y = input.nextInt();
    		System.out.println();
    		int result = x * y;
    		return result;
    	}
    Why can't it see them in the function call

    Also, I still don't understand what's going on with the function call on line 11. Why are we using "Enter a product code: " for an argument instead of prompt or str? What was the point of even returning str if we're not even going to use it?
    //from StaticMethodExample.java
    private static Scanner sc = new Scanner(System.in);	
    	public static String getString(String prompt) {
    		System.out.print(prompt);
    		String str = sc.nextLine();
    		return str;
    	}
    And for that matter, what was the point of passing the so-called prompt argument, if we're using "Enter a product code: "? I'm so confused.

    Quote Originally Posted by jim829 View Post
    An instance of the class is not required.
    Are you saying we don't need this:
    StaticMethodExample obj = new StaticMethodExample();
    		obj.printMessage();
    		obj.multiplyInts(x, y);
    That generates a warning message saying, "The static method printMessage() from the type StaticMethodExample should be accessed in a static way". With my inexperienced mind set, treating a static method like an object instance doesn't make sense to me either.

  8. #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: Trouble calling static methods from another class

    program wants me to define the x and y arguments.
    A variable is defined by coding a data type like int or char or a class like String:
       int anInt;     //  defines an int variable
       String aStr; // defines a reference to a String object.
       int anotherInt  = 3;    // defines an int variable and assigns it a value

    The code must define a variable before it is used. The definition must be in scope (within same {}s) with where it is used.

    The variables x and y are NOT defined in scope with where they are used. You need to Add definitions for those variables.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Member
    Join Date
    Dec 2018
    Location
    Wisconsin
    Posts
    54
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Default Re: Trouble calling static methods from another class

    Quote Originally Posted by Norm View Post
    The variables x and y are NOT defined in scope with where they are used. You need to Add definitions for those variables.
    Norm, I bit the bullet and tried what you said, but my worst fears have been realized. If you don't initialize the int variables, they generate the "The local variable result may not have been initialized" error when you try to use them in the code. If you do initialize them to 0, the console output looks like this:
    ScopeInitializationProblems.PNG
    Here are my two latest .java classes that caused that ouput:
    package randomExperiments;
     
    import java.util.Scanner;
    /*
    Influenced from page 117 in textbook. 
    */
    public class StaticMethodExample {
     
    	private static Scanner sc = new Scanner(System.in);	
    	public static String getString(String str) {
    		System.out.print("Enter a string for the str variable: ");
    		str = sc.nextLine();
    		return str;
    	}
    	//to call this method in another class: String myString = StaticMethodExample.getString(str);
     
    	public static void printMessage(){
    		System.out.println("Hello. I'm from a static void method, printMessage().");
    	}
    	//to call this method in another class: StaticMethodExample.printMessage();
     
    	public static int multiplyInts(int x, int y, int result){
    		Scanner input = new Scanner(System.in);
    		System.out.print("Enter an int value for x: ");
    		x = input.nextInt();
    		System.out.println();
    		System.out.print("Enter an int value for y: ");
    		y = input.nextInt();
    		System.out.println();
    		result = x * y;
    		return result;
    	}
    	//to call this method in another class: StaticMethodExample.multiplyInts(x, y);
    }
    package randomExperiments;
     
    import java.util.Scanner;
    import java.util.Random;
    import static randomExperiments.StaticMethodExample.*;
     
    public class RandomExperiments {
     
    	public static void main(String[] args){		
    		int x = 0, y = 0, result = 0;//note that initializing "result = x * y" here does nothing.
    		String str = "";
    		String myString = StaticMethodExample.getString(str);
    		System.out.println("The string passed from the my string function is: " + myString);
    		StaticMethodExample.printMessage();
    		StaticMethodExample.multiplyInts(x, y, result);
    		System.out.println("You entered " + x + " for x, and " + y + " for y.\n");
    		System.out.println("x * y = " + result);		
    	}
    }

    This is starting to bum me out. I thought Java was smarter than this. So how do I get the x and y defined in the multiplyInts function to overwrite the x and y variables initialized to 0 in the randomExperiments.java class?

  10. #10
    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: Trouble calling static methods from another class

    Please copy the full text of any error messages and paste them here so we can see them. Don't post images as their contents can not be copied to include in a response.

    initializing "result = x * y" here does nothing.
    It does what it is coded to do: multiply the current contents of x by y and assign the product to result. When that statement is executed, the values of x and y is 0.

    The multiplyInts method's definition:
    	public static int multiplyInts(int x, int y, int result){
    says it takes three int values as arguments and returns an int value. There should only be two arguments (x and y) passed to the method.
    The int value that is returned by the method needs to be saved in the result variable:
       result = StaticMethodExample.multiplyInts(x, y);
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Member
    Join Date
    Dec 2018
    Location
    Wisconsin
    Posts
    54
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Default Re: Trouble calling static methods from another class

    Interesting. Line 15 finally did what I wanted for result:
    package randomExperiments;
     
    import java.util.Scanner;
    import java.util.Random;
    import static randomExperiments.StaticMethodExample.*;
     
    public class RandomExperiments {
     
    	public static void main(String[] args){		
    		int x = 0, y = 0, result = 0;//note that initializing "result = x * y" here does nothing.
    		String str = "";
    		String myString = StaticMethodExample.getString(str);
    		System.out.println("The string passed from the my string function is: " + myString);
    		StaticMethodExample.printMessage();
    		result = StaticMethodExample.multiplyInts(x, y);
    		System.out.println("You entered " + x + " for x, and " + y + " for y.\n");
    		System.out.println("x * y = " + result);		
    	}
    }

    However, the concatenated print statement on line 16 still thinks I want to print out 0's:
    Enter a string for the str variable: megaman
    The string passed from the my string function is: megaman
    Hello. I'm from a static void method, printMessage().
    Enter an int value for x: 3
     
    Enter an int value for y: 3
     
    You entered 0 for x, and 0 for y.
     
    x * y = 9

    This isn't a huge deal, but I'll ask anyway. How do I get it to say "You entered 3 for x, and 3 for y." instead?

  12. #12
    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: Trouble calling static methods from another class

    I want to print out 0's:
    Where are x and y given values in that method where those variables are defined? They are given a value of 0 when they are defined and that value is never changed in the method where their values are being printed.

    The problem is the values (0) of the variables (x and Y) are passed to the method and received in the method in locally defined variables with the same names. Changing the values of those local variables in the multiplyInts method does not change the value of the variables in the main() method which remain at 0.
    Using the same names might be confusing. Try changing the names in multiplyInts from x to operand1 and y to operand2 and use those new variable names to compute the product assigned to result.

    How do I get it to say "You entered 3 for x, and 3 for y." instead?
    The prompts the values of x and y must be done in the main method so that their values are changed there. Then those values should be passed to the multiplyInts method.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Member
    Join Date
    Sep 2018
    Location
    Virginia
    Posts
    284
    My Mood
    Cool
    Thanks
    0
    Thanked 38 Times in 36 Posts

    Default Re: Trouble calling static methods from another class

    Ok, I get the impression that you don't fully understand what purpose a method serves.
    Can you explain it in general terms?

    public int someMethod(int a, int q, int b) {
    // method body
    // and return
    }

    Regards,
    Jim

  14. #14
    Member
    Join Date
    Dec 2018
    Location
    Wisconsin
    Posts
    54
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Default Re: Trouble calling static methods from another class

    Quote Originally Posted by Norm View Post
    The prompts the values of x and y must be done in the main method so that their values are changed there. Then those values should be passed to the multiplyInts method.
    Yes! Finally my program works:
    package randomExperiments;
     
    import java.util.Scanner;
    /*
    Influenced from page 117 in textbook. 
    */
    public class StaticMethodExample {
     
    	private static Scanner sc = new Scanner(System.in);	
    	public static String getString(String str) {
    		System.out.print("Enter a string for the str variable: ");
    		str = sc.nextLine();
    		return str;
    	}
    	//to call this method in another class: String myString = StaticMethodExample.getString(str);
     
    	public static void printMessage(){
    		System.out.println("Hello. I'm the static void method, printMessage().");
    	}
    	//to call this method in another class: StaticMethodExample.printMessage();
     
    	public static int multiplyInts(int x, int y){
    		int result = x * y;
    		return result;
    	}
    	//to call this method in another class: StaticMethodExample.multiplyInts(x, y);
    }
    package randomExperiments;
     
    import java.util.Scanner;
    import java.util.Random;
    import static randomExperiments.StaticMethodExample.*;
     
    public class RandomExperiments {
     
    	public static void main(String[] args){		
    		int x = 0, y = 0, result = 0;
    		Scanner input = new Scanner(System.in);
    		System.out.print("Enter an int value for x: ");
    		x = input.nextInt();
    		System.out.println();
    		System.out.print("Enter an int value for y: ");
    		y = input.nextInt();
    		System.out.println();
    		String str = "";
    		String myString = StaticMethodExample.getString(str);
    		System.out.println("The string passed from the my string function is: " + myString);
    		StaticMethodExample.printMessage();
    		result = StaticMethodExample.multiplyInts(x, y);
    		System.out.println("You entered " + x + " for x, and " + y + " for y.\n");
    		System.out.println("x * y = " + result);		
    	}
    }
    Output:
    Enter an int value for x: 3
     
    Enter an int value for y: 3
     
    Enter a string for the str variable: dink
    The string passed from the my string function is: dink
    Hello. I'm the static void method, printMessage().
    You entered 3 for x, and 3 for y.
     
    x * y = 9
    Quote Originally Posted by jim829 View Post
    Ok, I get the impression that you don't fully understand what purpose a method serves.
    The real stumbling block (for me) is managing scope, not understanding the idea of it. Before I declared x and y and initialized them to 0 in the main method, the dumb program wouldn't even let me pass the real x and y arguments to the function call. I guess I was expecting too much to happen in one method definition.

    Thank you again, Jim and Norm.

Similar Threads

  1. Threads calling static and non-static method
    By dhasija in forum What's Wrong With My Code?
    Replies: 1
    Last Post: July 14th, 2014, 06:05 AM
  2. Accessing non-static methods from action listener in another class?
    By mfj in forum What's Wrong With My Code?
    Replies: 3
    Last Post: March 10th, 2013, 06:23 PM
  3. Problem with calling objects from same-class methods in main
    By thekbon in forum Object Oriented Programming
    Replies: 12
    Last Post: December 18th, 2012, 01:10 AM
  4. Why and where abstract methods & classes and static methods are used?
    By ajaysharma in forum Object Oriented Programming
    Replies: 7
    Last Post: July 14th, 2012, 01:16 AM
  5. Calling a void method into a static void main within same class
    By sketch_flygirl in forum Object Oriented Programming
    Replies: 3
    Last Post: November 15th, 2009, 05:24 PM