2014-09-01 2 views
1

이제는 내 문제입니다. ArrayList에서 둘 이상의 영업 담당자의 연간 판매량을 비교하려고하고 있는데, 알아낼 수없는 몇 가지 이상한 결과가 나타납니다. 나는이 두 가지를 비교해야만한다. 그러면 더 낮은 매출을 가진 담당자가 얼마나 많은 돈을 팔아서 주도해야 하는지를 사용자에게 말해야한다. 나는 그것을 세 가지 수업으로 나누었다. 그러나 나는이 행동이 그것들 중 단지 두 가지에 의존하고 있음을 확신합니다. 첫째는이 하나의 사용자에게 표시하면서Java의 배열 목록에서 rep 영업을 비교하려고 시도합니다.

import java.util.ArrayList; 

/** 
* 
* @author Cameron 
*/ 
public class SalesRep { 

private ArrayList<CompensationCalculator> pool; 

public SalesRep(){ 

    pool = new ArrayList<>(); 

} 

public void setPool(ArrayList<CompensationCalculator> pool){ 

    this.pool = pool; 

} 

public ArrayList<CompensationCalculator> getPool(){ 

    return pool; 

} 

public void addToPool(CompensationCalculator salesRep){ 

    pool.add(salesRep); 

} 

public String toString(String report){ 

    double diff; 

    for(int i=0; i<pool.size(); i++){ 

     if (pool.get(i).getSales() < pool.get(i++).getSales()){ 

      diff = pool.get(i++).getSales() - pool.get(i).getSales(); 
      report = pool.get(i).getName() + "needs to sell " + 
        diff + " to take the lead."; 
     }    

     if (pool.get(i).getSales() > pool.get(i++).getSales()){ 

      diff = pool.get(i).getSales() - pool.get(i++).getSales(); 
      report = pool.get(i++).getName() + "needs to sell " + 
        diff + " to take the lead."; 
     } 

     } 
    return report; 
    } 
} 

클래스 배열에서 두 담당자 비교해야

import java.util.Scanner; 

public class AnnualSales { 

public static void main(String[] args){ 

    CompensationCalculator test = new CompensationCalculator(); //Creates a new instance of the class 
    SalesRep testName = new SalesRep(); //Creates a new instance of the SalesRep class 
    String cont = new String(); //A string to represent if there ar emore names to be added 

    Scanner scan = new Scanner(System.in); //Allows for user input to be read 

    while (!cont.equalsIgnoreCase("n")){ 

     System.out.println("What is the name of the sales representative? "); 
      test.setName(scan.next()); 

     System.out.println("Please enter " + test.getName() + 
       "'s annual sales: "); 
      test.setSales(scan.nextDouble()); 

     testName.addToPool(test); 

     System.out.println("Are there any more sales representatives you " 
       + "would like to add? "); 
      cont = scan.next(); 

     } 

    System.out.print(testName.getPool()); 
    System.out.print(testName.toString()); 
    } 
} 

지금 발견되는 오류가없는 프로그램은 컴파일 실행한다 문제없이. 그러나 그 결과로 내가 얻을

`[[email protected], [email protected]] [email protected] '

나는 매우 혼란 스러워요 3 시간 때문에 단지이 방법에 노력하고있다 나는 신선한 쌍의 눈이 필요하다고 확신한다. 어떤 도움이나지도라도 훌륭 할 것입니다.

편집 :

비교기를 사용하도록 제안 deffinetely 도움이되었다 있도록

좋아. 불필요한 코드로 혼란스러워서 조금만 고쳤으며 지금은 한 가지 측면을 제외하고는 작동하고 있습니다. 다음은 내가 변경 한 코드입니다.

public String compare(SalesRep rep1, SalesRep rep2){ 

    NumberFormat fmt = NumberFormat.getCurrencyInstance(); 
    Double diff; 

    if (rep1.getSales() > rep2.getSales()){ 
     diff = rep1.getSales() - rep2.getSales(); 
     return rep2.getName() + " needs to sell " + fmt.format(diff) + 
       " to take the lead.";} 
    else{ 
     diff = rep2.getSales() - rep1.getSales(); 
     return rep1.getName() + " needs to sell " + fmt.format(diff) + 
       " to take the lead.";}     
     } 

또한 새로운 요구 사항을 고려하여 클래스를 더 잘 구성하도록 이름을 변경했습니다. 이제 유일한 문제는 두 판매의 차이를 0.0 달러로 제공한다는 것입니다. 각 물체 판매를 잘못 부르겠습니까? 이전에이 문제를 겪었지만 내 과거 코드를 검토하는 것이 내가 잘못하고있는 것을 강조 표시하지 않는 것 같습니다.

+0

[? 저를 클릭하세요] (http://stackoverflow.com/questions/17878457/what-is -the-it-it-shows-when-i-print-out-this-java/17878495 # 17878495) –

답변

1

나는 toString(String)으로 전화를 걸지 만 toString() 만 전화하면 그 "stange"출력을 얻을 수 있습니다.

Btw, 메서드의 report 매개 변수는 할당 외에도 사용하지 않으므로 상당히 이상하게 보입니다. 이 경우 로컬 변수를 사용해야합니다.

또 다른 잠재적 인 오류 : 당신이 pool에서 3 개 가지 지표를 참조 것, 그래서 여기에

if (pool.get(i).getSales() > pool.get(i++).getSales()){ 
    diff = pool.get(i).getSales() - pool.get(i++).getSales(); 
    report = pool.get(i++).getName() + "needs to sell " + 
      diff + " to take the lead."; 
} 

하면, i 세 번 증가하고 있습니다. i = 0을 가정 , 당신은 얻을 것이다 : 루프의 머리에 i++도 내가 한 번 더 증가하기 때문에

//the first i++ returns i (0) and then increments i to 1 
if (pool.get(0).getSales() > pool.get(0).getSales()){ 
    //here i is 1, thus the next i++ returns 1 and increments i to 2 
    diff = pool.get(1).getSales() - pool.get(1).getSales(); 
    //here i is 2, so the next i++ returns 2 and increments i to 3 
    report = pool.get(2).getName() + "needs to sell " + 
      diff + " to take the lead."; 
} 

그래서 그 두 번째 경우에 당신이 4 루프를 i 3을 추가하고, 따라서 사전 것입니다. i++ 대신 루프 본문에 i + 1을 사용하는 것이 좋습니다.

게다가, CompensationCalculator 클래스가 실제로 판매 담당자를 정의하는 것처럼 보이기 때문에 디자인이 이상합니다.

또 다른 한 가지 : 영업 담당자 목록을 내림차순으로 정렬합니다 (힌트 : Comparator 사용).그러면 요소 0은 매출이 가장 높은 영업 담당자가되고 마지막 요소는 매출이 가장 낮은 영업 담당자가됩니다. 차이 계산은 그 때 케이크의 조각 일 것입니다.

0

호출중인 toString은 Object에서 상속 된 메서드입니다. 사용자가 정의한 toString 메서드는 String 매개 변수를 사용합니다.

System.out.print(testName.toString()); 

올바른 방법을 무시하십시오.

또는 귀하의 방법으로 반송 된 String을 사용하십시오.

String out; 
out = testName.toString(out); // Strings are immutable 
0

것은 당신의 toString 메소드 및 이동 보고서에 @Override 주석을 추가, 그래서 거짓말 :

@Override 
public String toString(){ 
    String report; 
    ..... 
} 
관련 문제