Welcome to Dream.In.Code
Become a Java Expert!

Join 149,507 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,340 people online right now. Registration is fast and FREE... Join Now!




Linking Classes between two separate files

 
Reply to this topicStart new topic

Linking Classes between two separate files

Js_Sol
14 Jul, 2007 - 09:33 PM
Post #1

New D.I.C Head
*

Joined: 14 Jul, 2007
Posts: 3



Thanked: 1 times
My Contributions
Hello,

What am I missing to get these files to "work together"? I'm sure I need a bit more around the EmployeeInfo aEmployee = new EmployeeInfo( ); area, but not sure what. I am not using arrays yet.... Thank You.

CODE
import java.util.Scanner;

public class Payroll
    
    {
            public static void main( String args[] )

         {
        

        Scanner input = new Scanner ( System.in );
    double hourlyPay;
    double hoursWorked;
    double sum;
System.out.println();
System.out.print("Payroll Calculation Program\nPlease type STOP to end program");
System.out.println();
System.out.println();
System.out.println();
System.out.print("Enter Employee Name:");
String empName = input.nextLine();

EmployeeInfo aEmployee = new EmployeeInfo(  );
while ( !empName.equalsIgnoreCase("stop") )
      {
    System.out.printf( "Enter Hourly Rate for %s: $",empName );
            hourlyPay = input.nextDouble();
            while (hourlyPay < 0.00) {
            System.out.print("Please re-enter using positive numbers only: $");
            hourlyPay = input.nextDouble();
}
            System.out.print ( "Enter Hours Worked: ");
            hoursWorked = input.nextDouble();
            while (hoursWorked < 0.00) {
            System.out.print ("Please re-enter using positive numbers only: ");
            hoursWorked = input.nextDouble();
}
            sum = hourlyPay * hoursWorked;
        
        System.out.printf ("%s's weekly pay is:$%.2f\n",empName,sum);
        System.out.println();
        

        input.nextLine();
            
                    System.out.print("Enter Employee Name:");              
                    empName = input.nextLine();
    
        
        }
}

}





Here is the other file

CODE
class EmployeeInfo
{

          
    public String empName;
        
    public double hourlyPay, hoursWorked;
    
    public EmployeeInfo()
    {
        
      
        
    }
    
    public EmployeeInfo(String name, double hourlyPay, double hoursWorked)
    {
        
      this.empName = empName;
      this.hourlyPay = hourlyPay;
      this.hoursWorked = hoursWorked;  
        
    }
    
  
    public void setName(String name)
    {
        
        this.empName = empName;
        
    }
    
    
    public String getName()
    {
        
        return empName;
        
    }
    
    
    public void setHourlyPay(double hourlyPay)
    {
        
        this.hourlyPay = hourlyPay;
        
    }
    
  
    public double getHourlyPay()
    {
        
        return hourlyPay;
        
    }
    
    
    public void setHoursWorked(double hoursWorked)
    {
        
        this.hoursWorked = hoursWorked;
        
    }
    
    
    public double getHoursWorked()
    {
        
        return hoursWorked;
        
    }
    
    
    public double getWeeklyPay()
    {

    return hourlyPay * hoursWorked;        
        
    }
    
}


I need the EmployeeInfo class to store and retrieve the info designated in the Payroll class. Thank you again.

PS: I am using a friends study supplies to teach myself java as if I were a student. This is not mine, nor his homework... I just wanted to do real java studies. Thank you for understanding....

This post has been edited by Js_Sol: 14 Jul, 2007 - 09:38 PM
User is offlineProfile CardPM
+Quote Post

Martyr2
RE: Linking Classes Between Two Separate Files
15 Jul, 2007 - 08:50 AM
Post #2

Programming Theoretician
Group Icon

Joined: 18 Apr, 2007
Posts: 5,655



Thanked: 313 times
Expert In: C/C++, Java, VB, VB.NET, C#, PHP, Web Development, HTML & CSS, Javascript

My Contributions
Hello Js_Sol,

Before we get to the unveiling of my answer I wanted to point out a few things that may help you in the future with regards to programming something like this. I do understand you are probably new to the programming world, so don't take any of these comments to heart.

1) First, instead of using a bunch of println() calls, you can get the new lines by simply adding a newline character in your printed comments. Notice I took them out and instead added some "\n" to the output, this will give you new lines and won't cause extra function calls which will slow your program down.

2) Notice that even though I setup an EmployeeInfo variable, I do not set it to an instance of the object until I have all my information available. No need to set this up at the beginning of the program loop. I will set it only after I can give it valid info. This is known as throwing the object into a valid state.

3) In your EmployeeInfo object, you did a very good job setting this up. Again, to make sure the object is in a valid state I setup a small call to your other constructor giving it valid information. The line that reads this("Unknown",0.00,0.00); is calling your other constructor.

4) In the weekly pay line at the end, notice now that we are using the object's methods to fetch the name and the pay of the specific employee. This will be great after you learn arrays because in this program you could easily store the employee in an array and move through the employees, asking each object to calculate its own pay.

5) Lastly I setup a helper function to prompt for a name. Now this isn't necessary, but the code can be called from different parts of your program and instead of repeating code, we can put it in its own function and call the function instead. This is known as refactoring since we took it out of main flow and made it its own function to then call whenever we please. Notice I make two calls to the function. If I left it in, I would have had to repeat the same lines again. Doing it this way, with its own function, I cut down on repeat code, I reduce the complexity of the project, and I can make it more maintainable for programmers later.

Now for the solution. This is still in a rough state and by no means bulletproof. If you enter letters in for pay or hours, you are going to get errors. Since I don't think you have gotten to error handling yet, I will hold off on showing any of that. This code has been tested and works great. Hopefully it is what you are looking for to get you that push in the right direction.

EmployeeInfo.java

CODE

class EmployeeInfo
{    
    public String empName;
    public double hourlyPay, hoursWorked;
    
    public EmployeeInfo()
    {
          this("Unknown",0.00, 0.00);  
    }
    
    public EmployeeInfo(String name, double hourlyPay, double hoursWorked)
    {
          this.empName = name;
          this.hourlyPay = hourlyPay;
          this.hoursWorked = hoursWorked;  
    }
    
  
    public void setName(String name)
    {  
          this.empName = empName;  
    }
    
    
    public String getName()
    {
          return empName;
    }
    
    
    public void setHourlyPay(double hourlyPay)
    {
          this.hourlyPay = hourlyPay;
    }
    
  
    public double getHourlyPay()
    {
          return hourlyPay;
    }
    
    
    public void setHoursWorked(double hoursWorked)
    {
          this.hoursWorked = hoursWorked;
    }
    
    
    public double getHoursWorked()
    {
          return hoursWorked;
    }
    
    
    public double getWeeklyPay()
    {
          return hourlyPay * hoursWorked;
    }  
}


Payroll.java

CODE

import java.util.Scanner;

public class Payroll
{
    public static void main( String args[] )
    {
                Scanner input = new Scanner ( System.in );
                double hourlyPay;
                double hoursWorked;
                double sum;

                System.out.print("\nPayroll Calculation Program\nPlease type STOP to end program\n\n\n");

                // Create an EmployeeInfo variable
                EmployeeInfo aEmployee;

                String empName = askForName(input);

                while ( !empName.equalsIgnoreCase("stop") )
                {
                        // Ask for hourly pay
                        System.out.printf( "Enter Hourly Rate for %s: $",empName );
                        hourlyPay = input.nextDouble();
                        while (hourlyPay < 0.00) {
                                System.out.print("Please re-enter using positive numbers only: $");
                                hourlyPay = input.nextDouble();
                        }

                        // Ask for hours worked
                        System.out.print ( "Enter Hours Worked: ");
                        hoursWorked = input.nextDouble();

                        while (hoursWorked < 0.00) {
                                System.out.print ("Please re-enter using positive numbers only: ");
                                hoursWorked = input.nextDouble();
                        }

                        // Now setup our employee using the name, pay, and hours worked to initialize it.
                        aEmployee = new EmployeeInfo(empName, hourlyPay, hoursWorked);

                        // Display the name and weekly pay using our object.
                        System.out.printf ("%s's weekly pay is: $%.2f\n\n", aEmployee.getName(), aEmployee.getWeeklyPay());
        
                        input.nextLine();
                        empName = askForName(input);
                }
        }


        // This helper method prompts the user for an employee name.
        // It takes in a Scanner object as a parameter.

        private static String askForName(Scanner input) {
                System.out.print("Enter Employee Name: ");
                String empName = input.nextLine();

                // If they didn't give us a name, ask again.
                while (empName.equals("")) {
                        System.out.print("Enter Employee Name: ");
                        empName = input.nextLine();    
                }
                return empName;
        }
}


Enjoy!


User is offlineProfile CardPM
+Quote Post

Js_Sol
RE: Linking Classes Between Two Separate Files
15 Jul, 2007 - 12:53 PM
Post #3

New D.I.C Head
*

Joined: 14 Jul, 2007
Posts: 3



Thanked: 1 times
My Contributions
Thank you Martyr2, You new code is definetely smoother than mine. I compiled and ran it and it works great, but I still don't feel it's really using the employeeInfo class at all. It seems like Payroll still does all the work. How would you recommend just setting up just one preset employee that could be typed in, and the info would pull from the employee info file?

I'm goin to read about arrays so by the time you answer that /have the code I should be able to had an arraylist to it. Thank you for helping to teach me!
User is offlineProfile CardPM
+Quote Post

1lacca
RE: Linking Classes Between Two Separate Files
15 Jul, 2007 - 01:36 PM
Post #4

code.rascal
Group Icon

Joined: 11 Aug, 2005
Posts: 3,822



Thanked: 12 times
My Contributions
Excellent answer and explaining Martyr2!

QUOTE
1) First, instead of using a bunch of println() calls, you can get the new lines by simply adding a newline character in your printed comments. Notice I took them out and instead added some "\n" to the output, this will give you new lines and won't cause extra function calls which will slow your program down.


I have to add something here!
Using println or appending the '\n' char is not the same thing! println adds the platform dependent line separator character (as defined by the system property line.separator) that is not necessarily a single newline character ('\n'). It might not make any difference when writing to the console, but in other cases it might introduce some problems. However sometimes writing explicitly '\n' might be the good choice, it depends on the actual situation.
Also, the optimization aspect was true for previous JDKs, but right now javac together with the JIT compilers usually take care of this issue, and programmers can concentrate on writing readable code, and not "hand optimized" (I'm not saying here that a bunch of println is more readable, just that this kind of optimization is not of primary concern anymore) - even concatenating Strings with the + sign will be compiled to using a StringBuffer and Java won't create a bunch of temporary immutable String objects, it's the same thing as declaring public attributes for classes won't have any performance advantage over using accessor methods, since they will be optimized by the compilers, so writing "nice" code won't trash the performance.
Finally, optimization should be the last thing that happens to a code, and should be applied where it is necessary. If you can gain 10% speed improvement on a code that is in a loop that is executed a lot, then it's worth the effort, but here, when it is executed once, even 500% speed improvement doesn't worth the effort. On the other hand, I agree with you, that people must be aware of the performance of their code (and their coding habits), and avoid wasting resources.
OK, optimization is one of my favorite topics, so I felt that I had to add these thoughts.
User is offlineProfile CardPM
+Quote Post

Martyr2
RE: Linking Classes Between Two Separate Files
15 Jul, 2007 - 03:00 PM
Post #5

Programming Theoretician
Group Icon

Joined: 18 Apr, 2007
Posts: 5,655



Thanked: 313 times
Expert In: C/C++, Java, VB, VB.NET, C#, PHP, Web Development, HTML & CSS, Javascript

My Contributions
QUOTE(Js_Sol @ 15 Jul, 2007 - 01:53 PM) *

Thank you Martyr2, You new code is definetely smoother than mine. I compiled and ran it and it works great, but I still don't feel it's really using the employeeInfo class at all. It seems like Payroll still does all the work. How would you recommend just setting up just one preset employee that could be typed in, and the info would pull from the employee info file?

I'm goin to read about arrays so by the time you answer that /have the code I should be able to had an arraylist to it. Thank you for helping to teach me!



Actually the program is using the employee class a lot.

1) It asks the employeeinfo class for its name and its calculated weekly pay (remember these are defined by the object itself and the calculation is done in the object).

2) It uses the constructor of the object to create it.

The only thing the payroll program is actually doing is collecting and verifying the input from the user, which it should be doing.

Now as for your question, I am not too sure where this info file fits in. You didn't post anything about this file in the original question and didn't supply any file reading code. That functionality would be completely different than what you were attempting in the original code. Perhaps you can explain more about what you are trying to do?
User is offlineProfile CardPM
+Quote Post

Js_Sol
RE: Linking Classes Between Two Separate Files
15 Jul, 2007 - 03:09 PM
Post #6

New D.I.C Head
*

Joined: 14 Jul, 2007
Posts: 3



Thanked: 1 times
My Contributions
QUOTE(Martyr2 @ 15 Jul, 2007 - 04:00 PM) *

QUOTE(Js_Sol @ 15 Jul, 2007 - 01:53 PM) *

Thank you Martyr2, You new code is definetely smoother than mine. I compiled and ran it and it works great, but I still don't feel it's really using the employeeInfo class at all. It seems like Payroll still does all the work. How would you recommend just setting up just one preset employee that could be typed in, and the info would pull from the employee info file?

I'm goin to read about arrays so by the time you answer that /have the code I should be able to had an arraylist to it. Thank you for helping to teach me!



Actually the program is using the employee class a lot.

1) It asks the employeeinfo class for its name and its calculated weekly pay (remember these are defined by the object itself and the calculation is done in the object).

2) It uses the constructor of the object to create it.

The only thing the payroll program is actually doing is collecting and verifying the input from the user, which it should be doing.

Now as for your question, I am not too sure where this info file fits in. You didn't post anything about this file in the original question and didn't supply any file reading code. That functionality would be completely different than what you were attempting in the original code. Perhaps you can explain more about what you are trying to do?



Oh yeah...its cool.... Like I said, this whole task is based off my friends work studies just because I'm trying to teach myself java. I was just sort of "tricking it out" i suppose. I'm sure once I learn arrays I can do a bit more with it..... I'm mostly just having fun...

You rock Martyr2, thanks for the help..... if you want to show me something cool though, feel free to build the code using arrays and an user input to search for a specific employee. That way I'll know what it looks like once I know the stuff a bit. Thanks again tongue.gif
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/7/09 07:21PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month