2016-10-10 4 views
1

이 주제에 대한 여러 다른 게시물을 검토 한 결과 여기에서 이전에 설명한 내용을 다시 게시하는 경우 사과합니다. 여기 내 주요 방법은 내 테스트 클래스에서 호출하는 시험 방법 중 하나입니다 : 어떤 이유로 지금여러 클래스를 통해 java에있는 ArrayList에 객체 추가

public static void test1(){ 
     PolynomialA p = new PolynomialA(); 
     //should return true 
     System.out.println(p.isEmpty()); 
     if(p.isEmpty()){ 
      p.addTerm(2, 3); 
      p.addTerm(3, 2); 
      //should print (2)x^(3) + (3)x^(2) 
      System.out.println(p.toString()); 
      //should return false 
      System.out.println(p.isEmpty()); 
     } 
} 

, 용어는 용어를 추가되지 않으며, ArrayList를이 빈칸으로 추가 할 수 있습니다. 그래서, 아픈 쇼 당신 내 PolynomialA의 생성자 :

public class PolynomialA implements Quantity{ 

    private ArrayList<Term> list; 

    PolynomialA(){ 
     list = new ArrayList<Term>(); 
    }//end constructor 

그리고 내가 ArrayList를 목록에 (아래 표시됩니다) 용어를 추가하려고하고있는 addTerm() 메소드.

public void addTerm(int c, int e){ 
    Term temp; 

    for(int i = 0; i < list.size(); i++){ 
     //if a term with this exponent already exists in the polynomial 
     if(list.get(i).exponent == e){ 
      //just add the passed coefficient to the existing one 
      temp = new Term((list.get(i).coefficient + c), e); 
      list.set(i, temp); 
     }//end if 
     //else: a term with this exponent does not exist 
     else{ 
      //add the new term with the passed coeff and expo to the end 
      temp = new Term(c, e); 
      list.add(temp); 
     }//end else 
    }//end for 
}//end addTerm() 

전체 기간 클래스 : 계수, 및 지수 :

public class Term{ 

    int coefficient; 
    int exponent; 

    Term(){ 
     coefficient = 0; 
     exponent = 0; 
    } 

    Term(int c, int e){ 
     coefficient = c; 
     exponent = e; 
    } 
} 

그래서, 기본적으로, 다항식 용어 2 개 정수 연관된 값이 텀의 ArrayList를이다. PolynomialA 클래스 전반에 다른 많은 메소드가 있지만, 다른 클래스의 메소드를 작성하는 데 필요한 첫 번째 메소드입니다. 어떤 이유로 든 빈 ArrayList에 용어를 추가 할 수 없습니다. 나는 예외를 던지거나 아무것도 얻지 못하고있다. 그냥 ArrayList에 용어를 추가하지 않는다. 제발 도와주세요

또한, 코드 스 니핏 (snippits)이베이스 어쿠스틱 방식으로 여기에 배치되어 있다면 사과드립니다.

+0

배열 목록을 초기화 할 때 "무의미한"arraylist를 만들어야합니다. 그렇지 않으면 나는 방금 coeff와 엑스포로 하나를 만들었을 것입니다. – anon

+0

당신은 루프에 대해 공통적 인 초보자 실수를했습니다. 해당 지수가있는 용어가없는 경우 용어를 추가하려고합니다. 당신은 전체 목록을 보았을 때 그 지수가있는 용어가 있는지를 말할 수 없습니다. 그렇죠? 따라서 목록에 용어를 추가하는 코드는 루프 내부가 아닌 for 루프 이후에 발생해야합니다. – ajb

+1

@Joe 답변이 도착했을 때 질문을 삭제하는 것이 작동 방식이 아닙니다. 롤백. –

답변

2

모든 논리가 반복되어 목록을 반복합니다. 처음에는 목록이 비어 있으므로 루프 본문은 실행되지 않습니다.

귀하의 addTerm 방법은 다음과 비슷한 모습이 될 것입니다 귀하의 addTerm 클래스에서

public void addTerm(int c, int e){ 
    for (Term term : list) { // loop over the existing terms 
     if (term.exponent == e) { // if you find a matching one 
      term.coefficient += c; // update it's coefficient 

      return; // and return from the method 
     } 
    } 

    list.add(new Term(c, e)); // add a new term if no matching one was found 
} 
1

을, 당신은 루프를 가지고, 즉 I = 0 내가 <는 list.size INT에서 진행(). 귀하의 목록은 처음에는 0이므로 0 <입니다. 당신은 결코 루프 안으로 들어 가지 않습니다. 루프의 논리를 분할하는 것이 좋습니다. 먼저 값을 찾지 못했다면 항목을 확인한 다음 값을 루프 외부에 추가 할 수 있습니다.

public void addTerm(int c, int e){ 
    Term temp; 

    for(int i = 0; i < list.size(); i++){ 
     //if a term with this exponent already exists in the polynomial 
     if(list.get(i).exponent == e){ 
      //just add the passed coefficient to the existing one 
      temp = new Term((list.get(i).coefficient + c), e); 
      list.set(i, temp); 
     }//end if 
     //else: a term with this exponent does not exist 
     else{ 
      //add the new term with the passed coeff and expo to the end 
      temp = new Term(c, e); 
      list.add(temp); 
     }//end else 
    }//end for 
}//end addTerm() 
+0

코드가 OP와 다른 점은 무엇입니까? –