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

Thread: Can't call method from external class

  1. #1
    Junior Member zlloyd1's Avatar
    Join Date
    Nov 2012
    Location
    Norfolk, Virginia
    Posts
    25
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Can't call method from external class

    I am trying to call an external calls from a separate file within the same Java program, but it keeps telling me to create the method in the current class for some reason?? This floors me because I have used this method many times, and indeed twice within this same file, and it worked fine, but all of a sudden it will not compile it....
    Anyway, here is my code:
    package Annual;
    import java.util.*;
    public class Pay {
        private class Number{
        EmpChoice HM = new EmpChoice();
        HM.empChoice(); // keeps telling me to add this method, but it is added in the line above, isn't it??
     
        }
        public static void main(String[] args)
        {   double T = 50000; //set value for base salary                
            double Amt; //declare variable for final pay
            int x = 1;
         do{
          try{ //validate user input
            Scanner percent = new Scanner(System.in);
            System.out.println("Please enter annual sales:");//request user input
            System.out.println("Please enter valid dollar value:");
            double yearly = percent.nextDouble(); //store user input
               if (yearly >= 0 && yearly <= 500000){ //if over $500,000.00 in sales
               if (yearly >80000){ //if 80% sales goal was not reached
            double YrPrcnt = yearly * .05; //value used for compensation set next
            Amt = T + YrPrcnt * 1.25; //set Amt to pay plus commissions
            System.out.print("The Annual Payrate for employee is: $");
            System.out.println(Amt);}
               else {
                 System.out.print("The Annual Payrate for employee is: $"); 
                 System.out.println(T);
                 System.out.println();}}
                  else {
               System.err.print("Sales too high, ");
               System.err.println("please see Human Resources.");}
               x++; break;}
            catch(Exception e){ //if user input throws exception
                System.out.println("Try again please");}}while(x==1);
         CompensationChart C = new CompensationChart();
         CompensationChart C2 = new CompensationChart();
         C2.ListIt2(); // See, I did the exact same thing right here, and it worked fine????
         C.ListIt();}}
    This is the other class file code:
    package Annual;
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    public class EmpChoice
    {   @SuppressWarnings("empty-statement")
        public static void empChoice (String[] args) throws IOException
        {   
            Scanner EmpNum = new Scanner(System.in);
            System.out.println("How many employees will be evaluated?");
            //find out how many employees to work with....
            int HowMany = EmpNum.nextInt();
            int Emp;
            System.out.println("Enter employee name:");
            String string = "";
            InputStreamReader input = new InputStreamReader(System.in);
            BufferedReader reader = new BufferedReader(input);
                // read in user input        
            {string = reader.readLine();
            System.out.println(string);}}}
    and as you can see, there IS a method named empChoice in the class EmpChoice!! What am I doing wrong here please??


  2. #2
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Can't call method from external class

    You're trying to call a method where methods can't be called, out naked in the class. Methods should be called inside of constructors, other methods, or initializer blocks. The only exception is when you call a method to initialize a variable declared in the class. The solution is to call this method where it belongs, in the class's constructor or in another method.

    Some suggestions for the future:
    1. try to have your code comply with Java naming standards including starting variable and method names with lower-case letters. This makes your code easier for others to understand.
    2. If you ask a similar question, please post the actual compiler error message and don't try to paraphrase. The exact error message will tell us much as to what the actual problem may be.

  3. #3
    Junior Member zlloyd1's Avatar
    Join Date
    Nov 2012
    Location
    Norfolk, Virginia
    Posts
    25
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Question Re: Can't call method from external class

    Quote Originally Posted by curmudgeon View Post
    You're trying to call a method where methods can't be called, out naked in the class. Methods should be called inside of constructors, other methods, or initializer blocks. The only exception is when you call a method to initialize a variable declared in the class. The solution is to call this method where it belongs, in the class's constructor or in another method.

    Some suggestions for the future:
    1. try to have your code comply with Java naming standards including starting variable and method names with lower-case letters. This makes your code easier for others to understand.
    2. If you ask a similar question, please post the actual compiler error message and don't try to paraphrase. The exact error message will tell us much as to what the actual problem may be.
    Alright, I get what you are saying here, sort of, but when I try to call it from inside the main method it won't recognize it, and I think I am using correct coding....
    Anyway, here are the errors I am being thrown when I code it:HMclass.JPG and here are the compiler errors given when I try to run it:HMerror.JPG and although I know something is being done wrong on my part, I cannot for the life of me figure out what is happening here!!
    HM is initialized for the external class in this line of code: HMinitialized.JPG and the code for the external class being called is here:
    package Annual;
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    public class EmpChoice
    {   @SuppressWarnings("empty-statement")
        public static void empChoice (String[] args) throws IOException
        {   Scanner EmpNum = new Scanner(System.in);
            System.out.println("How many employees will be evaluated?");
            //find out how many employees to work with....
            int HowMany = EmpNum.nextInt();
            int Emp;
            System.out.println("Enter employee name:");
            String string = "";
            InputStreamReader input = new InputStreamReader(System.in);
            BufferedReader reader = new BufferedReader(input);
                // read in user input        
            {string = reader.readLine();
            System.out.println(string);}}}
    Is it because the initialization is outside of void main??
    Please tell me what is the problem here!!

  4. #4
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Can't call method from external class

    OK, please clarify just what you're trying to do. Also what is EmpChoice supposed to be doing? Why is its method static? And if it needs to be static, why create an EmpChoice instance? Why are you giving it a parater that is an array of String and then not using the parameter anywhere in your method? It almost looks as if you are trying to hijack main method code. If you have an error when you try try to call the method inside of main, you should show your attempt to do this and the new error message. Again, please be careful with your variable and method naming -- they should start with a lower case letter. Only classes, enums, interfaces, and the like should start with capital letters. Constants should be all-caps.

  5. #5
    Junior Member zlloyd1's Avatar
    Join Date
    Nov 2012
    Location
    Norfolk, Virginia
    Posts
    25
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Can't call method from external class

    To answer your questions, EmpChoice is one of three files, each with its own purpose in an employee payroll script I am working on. The only true functions of EmpChoice should be getting the number of employees that will be evaluated, and then being called within the main file, the Pay class. The Pay class in turn will accept some further information from the user, and call a third program file, which will be using an ArrayList to create a chart of potential commission based on employee sales for the year, which should return this value to the user using the Pay class....
    So there are three programs in one package, and project that I have, Pay, CommissionChart, and EmpChoice. The first one, Pay calls the other two and returns their values to the user. I am trying to get each part working before I try to combine them really, but I need to be confident that I can combine them when I am ready to, and this is hurting that confidence a bit. I just cannot see what it is saying is wrong, as being something that can be fixed. For instance, it will often have a gripe about this code block that makes no sense to me,
    EmpChoice HowMany() = new EmpChoice();
    It will return an error saying that I need define EmpChoice, which is being defined right there. It is almost like I was declaring a variable E as an int, and I write int desk; , and it gives me an error saying, Undefined parameter int, or another distinct possibility, Undefined parameter desk, and advises me to declare the in main.... The declaration is warning you that you need to declare!!
    As for the incorrect capitalization for style goes, I have gotten used to the way I name Java entities, and it would be terribly uphill for me to switch conventions now I think, but I will keep what you wrote in mind!!

  6. #6
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Can't call method from external class

    I'm still not clear on what the three classes are supposed to be doing. If you don't get a decent answer soon, consider clarifying the rolls, states and behaviors of the three classes you mention.

    As for the incorrect capitalization for style goes, I have gotten used to the way I name Java entities, and it would be terribly uphill for me to switch conventions now I think,...
    The conventions aren't for your benefit (at least not now), but for ours if you want us to be able to understand your code and be able to help you. I suggest you start making changes in your code now.

  7. #7
    Junior Member zlloyd1's Avatar
    Join Date
    Nov 2012
    Location
    Norfolk, Virginia
    Posts
    25
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Can't call method from external class

    Quote Originally Posted by curmudgeon View Post
    I'm still not clear on what the three classes are supposed to be doing. If you don't get a decent answer soon, consider clarifying the rolls, states and behaviors of the three classes you mention.



    The conventions aren't for your benefit (at least not now), but for ours if you want us to be able to understand your code and be able to help you. I suggest you start making changes in your code now.
    You did not understand what I wrote in my previous reply to you, as to what the classes were set up to accomplish?? Okay, well the first, and main class, called Pay, is supposed to call the class EmpChoice, which will request a number from the user. This number will be used to determine how many times the second class, CommissionChart will run. The class Pay, will also request an amount be entered by the user for annual sales made. This amount will be used to determine a total annual pay for the employee, which is based on commissions for sales made. All of this is then returned to the user in the form of a chart showing how much they have due to them, as well as a chart of potential compensations based on a range of annual sales amounts. So, class Pay, calls class EmpChoice, which prompts the user for information, which is then used to make a calculation of the user's annual pay based on a standard salary plus a commission amount based on total annual sales. This annual pay is returned to the user along with a chart of possible pay amounts with corresponding annual sales amounts, which is retrieved from class CommissionChart. All three classes are necessary to complete the process, but I am having problems calling them within class Pay....

    As to coding conventions, I believe I can see what you are saying there, and I will do my best to properly format any code posted on forums to accommodate your suggestions!!

  8. #8
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Can't call method from external class

    Quote Originally Posted by zlloyd1 View Post
    You did not understand what I wrote in my previous reply to you, as to what the classes were set up to accomplish??
    It's not as easy as you think, trying to understand someone else's creation. I hope that you continue to progress in your programming abilities and start helping others on this and other sites and you'll see what I mean. You'll also see how much fun and satisfying it can be.

    Okay, well the first, and main class, called Pay, is supposed to call the class EmpChoice, which will request a number from the user. This number will be used to determine how many times the second class, CommissionChart will run.
    One thing that confuses me is that in my mind something this basic, getting a single input from the user, can be done by a simple method of Pay rather than creating a whole other class, EmpChoice, whose only job is to hold a static method. So why this design decision? Will EmpChoice have other tasks? Will it have state (fields)?

    The class Pay, will also request an amount be entered by the user for annual sales made.
    So this input will be obtained from within Pay as opposed to the class to obtain a single number. Again this division seems a bit arbitray.

    This amount will be used to determine a total annual pay for the employee, which is based on commissions for sales made. All of this is then returned to the user in the form of a chart showing how much they have due to them, as well as a chart of potential compensations based on a range of annual sales amounts. So, class Pay, calls class EmpChoice, which prompts the user for information, which is then used to make a calculation of the user's annual pay based on a standard salary plus a commission amount based on total annual sales. This annual pay is returned to the user along with a chart of possible pay amounts with corresponding annual sales amounts, which is retrieved from class CommissionChart. All three classes are necessary to complete the process, but I am having problems calling them within class Pay....
    Based on your description EmpChoice will have nothing but a single static method, say called getCommissionChartCount(), that it will use a Scanner to prompt the user for input and will return an int for Pay to use. If you did it this way, you'd call the method off of the EmpChoice class, something like,

    // inside Pay
    int commissionChartCount = EmpChoice.getCommissionChartCount();

    Again, I would make this a non-static method in the Pay class (or it could be static if all Pay code is in static methods) and not a separate class, but either way would work.

    It would seem to me that a better class to create would be one called Employee that gets the salary and commission information and is able to calculate pay based on this.

  9. #9
    Junior Member zlloyd1's Avatar
    Join Date
    Nov 2012
    Location
    Norfolk, Virginia
    Posts
    25
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Smile Re: Can't call method from external class

    Quote Originally Posted by curmudgeon View Post
    It's not as easy as you think, trying to understand someone else's creation. I hope that you continue to progress in your programming abilities and start helping others on this and other sites and you'll see what I mean. You'll also see how much fun and satisfying it can be.



    One thing that confuses me is that in my mind something this basic, getting a single input from the user, can be done by a simple method of Pay rather than creating a whole other class, EmpChoice, whose only job is to hold a static method. So why this design decision? Will EmpChoice have other tasks? Will it have state (fields)?



    So this input will be obtained from within Pay as opposed to the class to obtain a single number. Again this division seems a bit arbitrary.



    Based on your description EmpChoice will have nothing but a single static method, say called getCommissionChartCount(), that it will use a Scanner to prompt the user for input and will return an int for Pay to use. If you did it this way, you'd call the method off of the EmpChoice class, something like,

    // inside Pay
    int commissionChartCount = EmpChoice.getCommissionChartCount();

    Again, I would make this a non-static method in the Pay class (or it could be static if all Pay code is in static methods) and not a separate class, but either way would work.

    It would seem to me that a better class to create would be one called Employee that gets the salary and commission information and is able to calculate pay based on this.

    "One thing that confuses me is that in my mind something this basic, getting a single input from the user, can be done by a simple method of Pay rather than creating a whole other class, EmpChoice, whose only job is to hold a static method. So why this design decision? Will EmpChoice have other tasks? Will it have state?"

    I need to break this up into three separate files, because the main class file, Pay will be secured once it is implemented, and I will not have access to it for revisions due to my somewhat low security rating here. I am well aware that all of this can be completed in a single program file, but I need to have three files for this project....

    "Again, I would make this a non-static method in the Pay class (or it could be static if all Pay code is in static methods) and not a separate class, but either way would work."

    I will go back and have another look at Pay, and see if I have classes or methods created as static, but I have to say that it seems to say "Trying to access static from non-static" even if I have nothing declared as static anywhere, like here static.JPG which is warning me about accessing a static from my main, but as you can see my main is also static??

    "Based on your description EmpChoice will have nothing but a single static method, say called getCommissionChartCount(), that it will use a Scanner to prompt the user for input and will return an int for Pay to use. If you did it this way, you'd call the method off of the EmpChoice class, something like,"


    Yes EmpChoice does only return a single user inputted int value, but as I said this is a three part project, so I had to make a whole new class just for that....

    Anyway, thanks for all the tips, and since this is still a work in progress, I will take everything you have suggested and try to work it in to what I am trying to complete here!!

Similar Threads

  1. Call class method from another class
    By NewbieJavaProgrammer in forum Object Oriented Programming
    Replies: 1
    Last Post: November 21st, 2012, 06:56 AM
  2. Can't call paint() method from another class
    By Huw in forum What's Wrong With My Code?
    Replies: 4
    Last Post: September 18th, 2012, 02:15 AM
  3. 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
  4. Call method(s) within the same class
    By mwr76 in forum Object Oriented Programming
    Replies: 8
    Last Post: September 26th, 2011, 12:58 AM
  5. Can i call init() method in destroy method.?
    By muralidhar in forum Java Servlet
    Replies: 1
    Last Post: October 22nd, 2010, 11:18 AM