2013-05-03 2 views
0

У меня есть программа, которая должна соответствовать этим требованиям: • Продавец будет продолжать получать фиксированную зарплату в размере 50 000,00 долларов США в год. Текущая цель продаж для каждого продавца составляет 120 000 долларов США в год. • Стимул продаж начнется только тогда, когда будет достигнуто 80% цели продаж. Текущая комиссия составляет 7,5% от общего объема продаж. • Если продавец превышает целевой показатель продаж, комиссия будет увеличиваться в зависимости от коэффициента ускорения. Коэффициент ускорения составляет 1,25. • Приложение должно попросить пользователя ввести годовой объем продаж и отобразить общую годовую компенсацию. • Приложение должно также отображать таблицу потенциальной общей ежегодной компенсации, которую продавец мог бы заработать в размере 5000 долларов США выше годового объема продаж продавца, пока он не достигнет 50% от годового объема продаж продавца.Вход и выход ArrayList в Java

• The application will now compare the total annual compensation of at least two salespersons. 
  
• It will calculate the additional amount of sales that each salesperson must achieve to match or exceed the higher of the two earners. 
  
• The application should ask for the name of each salesperson being compared. 
• The application should have at least one class, in addition to the application’s controlling class. 
• The source code must demonstrate the use of conditional and looping structures. 
• The source code must demonstrate the use of Array or ArrayList. 

Там должна быть надлежащей документации в исходном коде

я смог построить таблицу с цикла. Моя проблема теперь - массив или ArrayList. Я построил ArrayList с классом Salesperson, но он не выводит getName. Что я делаю не так? Ниже приведены мои коды.

/* 
* Program: Salesperson.java 
* Written by: Amy Morin 
* This program will calculate total annual compensation for a salesperson. 
* Business requirements include: 
* Fixed salary = $50,000, sales target = $120,000, 
* sales incentive at 80% of sales, 
* Commission 7.5% of sales, if sales target is exceeded 1.25% increased 
* accelorated factor. 
* This program will also be the foundation to 
* compare two or more salespersons. 
*/ 

public class Salesperson 
{ 
    //Declares and initalizes fixed salary. 
    private final double Fix_Sal = 50000; 
    //Declares and initalizes commission. 
    private final double Comm = 7.5; 
    //Declares and initalizes acceleration factor. 
    private final double Accel_Factor = 1.25; 
    //Declares and initializes sales target. 
    double target = 120000;   
    //Declares and initializes sales incentive threshold. 
    double thresh = .80; 

    String spName; //holds the salesperson's name 
    double annSales; // Holds value for annual sales 
    double commRate; //holds calculated commission rate. 
    double commEarned; //holds calculated commission earned. 
    double totalAnnComp; //Holds calculated total annual commission 

    //Default Constructor 
    public Salesperson() 
    { 
     spName = "Unknown"; 
     annSales = 0.0; 
    } 

    ////parameterized constructor 
    public Salesperson(String name, double sales) 
    { 
     spName = name; 
     annSales = sales; 
    } 

    //The setName method will set the name of salesperson 
    public void setName(String name) 
    { 
     name = spName; 
    } 

    //The getName method will ruturn the name of salesperson 
    public String getName() 
    { 
     return spName; 
    } 

    //The setSales method will set the annual sales 
    public void setSales(double sales) 
    { 
     annSales = sales; 
    } 

    //The getSales method returns the value stored in annualSales 
    public double getSales() 
    { 
     return annSales; 
    } 

    //The getComm method will calculate and return commission earned 
    public double getComm() 
    { 
    //Check if sale are greater than or equal to 80% of target. 
    if (annSales >= (target * thresh)) 
    { 
      if (annSales > target) //Checks if annual sales exceed target. 
      { 
      //Gets commission rate. 
       commRate = (Comm * Accel_Factor)/100; 
     commEarned = commRate * annSales; 
      } 
      else 
      { 
     commRate = Comm/100; 
     commEarned = commRate * annSales; 
      } 
    } 
    else 
     { 
     commRate = 0; 
     commEarned = 0; 
    } 
    return commEarned; 
    } 

    /* 
    * The getAnnComp method will calculate and return the total 
    * annual compensation. 
    */ 
    public double getAnnComp() 
    { 
    totalAnnComp = Fix_Sal + commEarned; 
    return totalAnnComp; 
    } 
} 


/* 
* Program: SalespersonComparison 
* Written by: Amy Morin 
* This program will compare the total annual compensation 
* of at least two salespersons. It will also calculate the additional 
* amount of sales that each salesperson must achieve to match or 
* exceed the higher of the two earners. 
*/ 

import java.util.ArrayList; //Needed for ArrayList 
import java.util.Scanner; //Needed for Scanner class 
import java.text.DecimalFormat; //Needed for Decimal formatting 

public class SalespersonComparison 
{ 
    public static void main(String[] args) 
    {   
     final double Fix_Sal = 50000; //Declares and initiates fixed salary 
     double sales; // hold annual sales 

     //Create new ArrayList 
     ArrayList<Salesperson> cArray = new ArrayList<>(); 

     // Create a Scanner object to read input. 
     Scanner keyboard = new Scanner(System.in); 

     //Lets user know how to end loop 
     System.out.println("Press \'Enter\' to continue or type \'done\'" 
       + " when finished."); 

     //blank line 
     System.out.println(); 

     //Loop for setting name and annual sales of salesperson 
     do 
     { 
      //Create an Salesperson object 
      Salesperson sPerson = new Salesperson(); 

      //Set salesperson's name 
      System.out.println("Enter salesperson name"); 
      String name = keyboard.nextLine(); 
      sPerson.setName(name); 

      //End while loop 
      if (name.equalsIgnoreCase("Done")) 
       break;      

      //Set annual sales for salesperson 
      System.out.println("Enter annual sales for salesperson"); 
      sales = keyboard.nextDouble(); 
      sPerson.setSales(sales);   

      //To add Salesperson object to ArrayList 
      cArray.add(sPerson); 

      //Consume line 
      keyboard.nextLine();  
     } 
     while (true); 

     //Display ArrayList 

     DecimalFormat arrayL = new DecimalFormat("#,##0.00"); 
     for (int index = 0; index < cArray.size(); index++) 
     { 
      Salesperson sPerson = (Salesperson)cArray.get(index); 
      System.out.println(); 
      System.out.print("Salesperson " + (index + 1) + 
          "\n Name: " + sPerson.getName() + 
          "\n Sales: " + (arrayL.format(sPerson.getSales())) + 
          "\n Commission Earned: " + 
          (arrayL.format(sPerson.getComm())) + 
          "\n Total Annual Compensation: " 
          + (arrayL.format(sPerson.getAnnComp())) + "\n\n"); 



     } 
    } 
}  

Output 
Press 'Enter' to continue or type 'done' when finished. 

Enter salesperson name 
amy 
Enter annual sales for salesperson 
100000 
Enter salesperson name 
marty 
Enter annual sales for salesperson 
80000 
Enter salesperson name 
done 

Salesperson 1 
Name: Unknown 
Sales: 100,000.00 
Commission Earned: 7,500.00 
Total Annual Compensation: 57,500.00 


Salesperson 2 
Name: Unknown 
Sales: 80,000.00 
Commission Earned: 0.00 
Total Annual Compensation: 50,000.00 

BUILD SUCCESSFUL (total time: 20 seconds) 

Как только я рисую эту проблему, тогда мне нужно выяснить, как добавить таблицу и выполнить сравнение.

+3

Ваш вопрос слишком длинный. Идите прямо к делу, только вставьте соответствующий код и четко объясните, что должен делать этот соответствующий код и что он делает. –

+2

Это явно проблема домашних заданий - поэтому я не буду отвечать напрямую. Но изучите ваши геттеры и настройки. –

+2

Все уже дали вам ответ, но, как отмечает @JerryAndrews, проблема связана с вашими геттерами и сеттерами. Это была бы отличная возможность использовать отладчик ;-) –

ответ

1

Вы назначаете значения в обратном порядке.

//The setName method will set the name of salesperson 
public void setName(String name) 
{ 
    name = spName; 
} 

Должно быть

//The setName method will set the name of salesperson 
public void setName(String name) 
{ 
    spName = name; 
} 
+0

user1681360, спасибо, я даже не заметил эту простую маленькую ошибку, иногда она принимает свежие глаза. –

1

Проблема заключается в методе сеттер:

public void setName(String name) { 
    name = spName; 
} 

Вы назначая атрибут переменной. Исправить это так:

public void setName(String name) { 
    this.spName = name; 
} 

Чтобы избежать такого рода проблем, не забудьте использовать this ключевое слово в ваших добытчиках и присвоить параметр значения атрибута.

+1

Создание окончательных параметров также может помочь обнаружить такие ошибки. –

+0

Это сработало, Луиджи Мендоса, спасибо. Можете ли вы объяснить мне смысл этого. –

Смежные вопросы