2009-08-09 6 views
2

이제이 글을 읽었습니다.하지만 방금 막혔습니다. 어떤 도움을 주셔서 감사합니다. 나는 힌트를 찾고있다. 코드가 제대로 컴파일되고 실행되지만 변수가 직원 클래스에 저장되어 있다고 생각하지 않으며 생성자 권한을 올바르게 사용하고 있는지 잘 모르겠습니다.Java Help : 클래스 사용

요구 사항 : 나는 완료 :

값은 긍정적 인 숫자 확인하기 위해 검사합니다.

직원 이름 끝 프로그램으로 중지가 시작됩니다.

갖는 문제는

  • 이름
  • 시간당 요금
  • 시간가 empl를 초기화하기 위해 사용을 생성자를

근무 저장하는 클래스를 사용 oyee 정보 및 그 클래스 내의 메소드 에 대한 주간 지불을 계산합니다. 여기

+0

"문제가있는"것은 질문이 아닙니다. 귀하의 질문은 무엇인가? 무슨 일 이니? 컴파일러에서 무엇을 말하고 있습니까? – spender

+0

나는 질문을 이해하지 못한다 : – programmernovice

+0

내 질문을 명확히했다. 빠른 코멘트 주셔서 감사합니다! – gooddadmike

답변

2

는 몇 가지 힌트입니다 :

제공된 코드를 찾고 직원 정보

를 초기화하는 생성자를 사용하여, 인수를 취하지 않고하는 하나의 생성자가있다 개체의 필드를 0으로 초기화하십시오.

아마도 "직원 정보를 초기화하는 생성자"는 생성자가 Employee 개체가 해당 필드를 초기화해야하는 값을 받아 들일 수 있어야한다는 것을 의미합니다.

The Java Tutorials 페이지는 Providing Constructors for Your Classes에 있으며 이러한 생성자를 만드는 데 도움이되는 예제가 있습니다.

... 그리고 에 그 클래스 내에서 메소드는 주급이 단지 자체에 보이는 순서에서 다른 사람들로부터 사용할 수없는 방법이되어야한다고 말하는 것 같다

을 계산 weeklyPay 필드의 값을 계산하십시오.

다시 The Java Tutorials에서 Controlling Access to Members of a Class은 방법의 가시성을 변경하는 것으로 설명합니다.

Lesson: Classes and ObjectsThe Java Tutorials 인 것을 보아도 될 것 같습니다. 객체 지향 프로그래밍의 개념에 대한 좋은 예와 설명을 제공하기 때문에 유용 할 수 있습니다.

1

메서드을 작성하여 주간 임금을 계산하도록 요청하는 동안 이름, 시간당 요율 및 근무 시간을 저장하는 클래스를 만들라는 메시지가 나타납니다. 즉, weeklyPay 인스턴스 변수가 없어야합니다. 사용자가 getWeeklyPay() 메서드를 사용하여 주간 지불을 요청할 때마다 인스턴스 변수에 저장하지 않고 직접 계산하여 반환합니다.

실제로 그 결과를 사용하기 위해 그런 다음이 변경해야합니다 :

weeklyPay = employee.getWeeklyPay(); 

는 당신이 실제로 결과를 할당하지 않으면이 같은 무언가로

Employee.getweeklyPay();// Calculate weeklyPay (hoursWorked * hourlyRate) 
weeklyPay = (hoursWorked * hourlyRate); 

을 일부 변수에 메소드를 사용하면 결과를 사용할 수 없습니다.

2

다른 사람이 언급 한 것처럼 생성자를 사용하여 변수를 설정하지 않았다는 사실 외에도. setter 메소드는 아무런 작업도 수행하지 않습니다. 그래서 당신이 기대하는 결과를 얻지 못하고있는 것입니다. 로컬 var를 멤버 var가 아닌 자체로 설정합니다.

당신은 해당 지역의 VAR 이름을 변경 멤버 VAR 이름을 변경하거나 '이'키워드를 사용하는 setter를 변경하거나 필요

public void sethoursWorked(float hoursWorked) 
{ 
    this.hoursWorked = hoursWorked; 
} 
0

영업에서 최종 답변 :

/** Payroll3.java | Due 8/09/09 
** IT 2015 Java Programming | lazfsh | Axia College - University of Phoenix */ 

import java.util.Scanner;// Import and use scanner 

public class Payroll3 {// main method begins 
    public static void main(String args[]) { 

    // Initialize 
    boolean stop = false;// Variable for exit procedure 
    String endProgram = "";// Variable to explain exit procedures blank 1st time 
    int version = 3;// Version number 

    // Welcome message 
    System.out.printf( 
    "\nWelcome to the Payroll Program v.%d\n", version);//Welcome message  

    while (stop == false) {// Run program until stop equals true 

     Scanner input = new Scanner(System.in);// new Scanner for CL input 
     Employee Employee = new Employee(); // new Employee constructor 

     // Prompt for and input name 
     System.out.printf("\nEnter name of the employee%s:", endProgram); 
     Employee.setempName(input.nextLine());// Accept input & Store 

     if (Employee.getempName().equals("stop")) {// If = end program w/message 
     System.out.printf("\n%s\n%s\n\n", "....", "Thanks for using Payroll Program"); 
     stop = true;} 
     else{// Continue retrieve hourlyRate, hoursWorked & Calculate 

     do {// Prompt for and input hourlyRate 
      System.out.printf("\n%s", "Enter hourly rate: $"); 
      Employee.sethourlyRate(input.nextFloat());// Accept input & Store 
      if (Employee.gethourlyRate() < 1) {// Show error for negative # 
       System.out.printf("%s", "Enter a positive number.");} 
      else;{}// Continue 
      } while (Employee.gethourlyRate() < 1);// End loop if positive number recieved 

     do {// Prompt for and input hoursWorked 
      System.out.printf("\n%s", "Enter number of hours worked:"); 
      Employee.sethoursWorked(input.nextFloat());// Accept input & Store 
      if (Employee.gethoursWorked() < 1) {// Show error for negative # 
       System.out.printf("%s", "Enter a positive number.");} 
      else;{}// Continue 
      } while (Employee.gethoursWorked() < 1);// End loop if positive number recieved 

     // Display formatted results 
     System.out.printf("\n%s's weekly pay is $%,.2f\nHourly rate ($%,.2f) multiplied by hours worked (%.0f)\n\n...Ready for next employee.\n\n", 
     Employee.getempName(), Employee.getweeklyPay(), Employee.gethourlyRate(), Employee.gethoursWorked()); 

// Debug Line   Employee.showVariables();   

     }// end retrieve hourlyRate, hoursWorked & Calculate 

     endProgram = (", \n(Or type \"stop\" to end the program)");//explain exit procedure on second empName prompt 

     }// ends program when stop equals true 

    }// end method main 

}//end class Payroll3 

직원 등급

/** Employee Class | Initializes and storeds data for employee 
     Also provides method to calculate weekly pay. 
*/ 

// Import statements 
import java.util.Scanner;// Import and use scanner 


public class Employee {//Begin Employee class 
    Scanner input = new Scanner(System.in);// new Scanner for CL input 

    // Declare instance variables 
    String empName; // Declare name as string 
    float hourlyRate; // Declare hourlyRate as float 
    float hoursWorked; // Declare hoursWorked as float 

    // constructor initializes employee information 
    public Employee() { // Initialize (clear) instance variables here 
     empName = ""; 
     hourlyRate = 0; 
     hoursWorked = 0; 
     } // end constructor 

    // Begin methods 
    public void setempName(String empName) {// public method to set the employee name 
     this.empName = empName;}// end method setempName 

    public String getempName() {// public method to get the employee name 
     return empName;}// end method getempName 

    public void sethourlyRate(float hourlyRate) {// public method to set the hourly Rate 
     this.hourlyRate = hourlyRate;}// end method set hourly Rate 

    public float gethourlyRate() {// public method to retrieve the hourly Rate 
     return hourlyRate;} // end method get hourly Rate 

    public void sethoursWorked(float hoursWorked) {// public method to set the hours Worked 
     this.hoursWorked = hoursWorked;} // end method set hours Worked 

    public float gethoursWorked() {// public method to retrieve the hours Worked 
     return hoursWorked;} // end method get hours Worked 

    public float getweeklyPay() {// public method to retrieve weekly Pay 
     return (hoursWorked * hourlyRate);}// end method get weeklyPay 

    /* Test line 
    public void showVariables(){ 
    System.out.printf("empName=%s, hourlyRate=%s, hoursWorked=%s", this.empName, this.hourlyRate, this.hoursWorked);} */ 

    } // end class Employee 
관련 문제