자바 다항식을 구하는 코드 만드는중인데요. read라는 메소드로 유저로부터 값을 입력받아야 되는데;;
가온길
package termNode;
public class termNode implements Comparable
{
private int coeff;
private int expon;
private termNode next;
public termNode()
{
coeff = 0;
expon = 0;
}
public termNode(int co, int ex)
{
coeff = co;
expon = ex;
}
public termNode(termNode c) //copy constructor
{
this.coeff = c.coeff;
this.expon = c.expon;
}
public int getCo()
{
return coeff;
}
public int getEx()
{
return expon;
}
public void setNext(termNode link)
{
next=link;
}
public termNode getNext()
{
return next;
}
public String toString()
{
return (Coefficient: + coeff + Exponent : + expon);
}
public int compareTo(Object other)
{
if (expon == ((termNode)other).expon)
return 0;
else if (expon ((termNode)other).expon)
return -1;
else
return 1;
}
}package termNode;
public class polynomial
{
private termNode head;
public polynomial()
{
head = null;
}
public void append(int x, int y)
{
termNode newNode = new termNode(x, y);
} public void display()
{
if (head==null)
System.out.println(Empty List);
else
for (termNode cur=head; cur!=null; cur=cur.getNext())
System.out.println(cur);
}//end display
public void insert(termNode newNode)
{
termNode prev = null;
termNode cur = head;
while (cur != null && newNode.compareTo(cur)0)
{
prev=cur;
cur = cur.getNext();
}
if (prev==null) //insert at the beginning
{
newNode.setNext(head);
head = newNode;
}
else //insert in middle or at the end
{
newNode.setNext(cur);
prev.setNext(newNode);
}
}//end insert
public void read() //여기서 유저로부터 coeff 값이랑 expon값을 받아야되는데 어떻게 해야될지 잘 몰라서 대충 해봤거든요. 맨처음 head 를 null 로 설정한다음 해야되는데;;
{
this.head = null;
int coeff = 0;
int expon = 0;
head = new termNode(0,0);
while (coeff != 0 && expon != 0)
{
System.out.print(Enter coefficient: + coeff);
System.out.print(Enter exponent: + expon);
head = new termNode(coeff, expon);
insert(head);
}
}//end read
public polynomial add(polynomial a)
{
termNode p = this.head;
termNode q = a.head;
polynomial r = new polynomial();
while (p != null && q != null)
{
if (p.getEx() == q.getEx())
{
if (p.getCo() + q.getCo() == 0)
{
p = p.getNext();
q = q.getNext();
}
else
{
r.append(p.getEx(), p.getCo() + q.getCo());
p = p.getNext();
q = q.getNext();
}
}
else if (p.getEx() q.getEx())
{
r.append(q.getEx(), q.getCo());
q = q.getNext();
}
else
{
r.append(p.getEx(), p.getCo());
p = p.getNext();
}
}
while (p != null)
{
r.append(p.getEx(), p.getCo());
p = p.getNext();
}
while (q != null)
{
r.append(q.getEx(), q.getCo());
q = q.getNext();
}
return r;
}
}이래서 맨마지막 드라이버 클래스에서 polynomial p1 = new polynomial();polynomial p2 = new polynomial();polynomial p3 = new polynomial();p1.read();p2.read();이런식으로 한다음 p1다항식과 p2 다항식을 더해서 p3 에 저장시킨후 display 하는게 최종목표입니다. read(유저로부터 값을 받는메소드)코드좀 봐주시면 감사하겠습니다. 그리고 다른 코드로 잘못된거나 더 나아질수 있으면 답변 정말 감사하겠습니다.
-
데이비드
일단 콘솔에서 값을 받아서 출력하는것 부터 작성해 보셔야 하지 않나요?
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
reader.readLine();