이 주제에 대한 여러 다른 게시물을 검토 한 결과 여기에서 이전에 설명한 내용을 다시 게시하는 경우 사과합니다. 여기 내 주요 방법은 내 테스트 클래스에서 호출하는 시험 방법 중 하나입니다 : 어떤 이유로 지금여러 클래스를 통해 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)이베이스 어쿠스틱 방식으로 여기에 배치되어 있다면 사과드립니다.
배열 목록을 초기화 할 때 "무의미한"arraylist를 만들어야합니다. 그렇지 않으면 나는 방금 coeff와 엑스포로 하나를 만들었을 것입니다. – anon
당신은 루프에 대해 공통적 인 초보자 실수를했습니다. 해당 지수가있는 용어가없는 경우 용어를 추가하려고합니다. 당신은 전체 목록을 보았을 때 그 지수가있는 용어가 있는지를 말할 수 없습니다. 그렇죠? 따라서 목록에 용어를 추가하는 코드는 루프 내부가 아닌 for 루프 이후에 발생해야합니다. – ajb
@Joe 답변이 도착했을 때 질문을 삭제하는 것이 작동 방식이 아닙니다. 롤백. –