gpt4 book ai didi

java - 如何打印这个类的toString?

转载 作者:行者123 更新时间:2023-12-02 03:04:39 25 4
gpt4 key购买 nike

我编写了一个多项式类和一个测试器类。当提供了次数、系数和 x 的值时,多项式类可以计算并返回多项式的和。基本上我需要编辑我的 toString 方法,以便它实际上打印出多项式

          import java.util.Arrays;
import java.util.Scanner;
public class Polynomial {

private int degree;
private int [] coefficient;
private double evaluation;
private double sum;
private double value;
Scanner key = new Scanner(System.in);



public Polynomial(int degree)
{
this.degree = degree;
coefficient = new int [degree+1];

}


public void setCoefficient(int coefficient)
{
this.coefficient[this.degree] = coefficient;
}


public int getCoefficient(int degree)
{
return coefficient[degree];
}



public double Evaluate(double value)
{
this.value =value;
for (int i=0; i<=degree; i++)
{
System.out.println("Enter coefficent for position " + i);
this.coefficient[i] = key.nextInt();
evaluation = Math.pow(value, i)*this.coefficient[0] ;
this.sum += evaluation;

}
return sum;

}






/** Standard toString method */
//needed something better than this below...needed an actual polynomial printed out
public String toString()
{
return "The degree of the polynomial is " + degree + " and the value for which it has been evaluated is" + value;

}
}

最佳答案

这应该符合您应该继续进行的路线。为了简单起见,我将 main 函数包含在您的 Polynomial 类中,因此如果您想将其保留在测试器类中,则必须对其进行修改。请注意,level 已被制作成大小为 level +1 的整数数组(在构造函数中分配):

import java.util.Scanner;
public class Polynomial {

private int degree;
private int [] coefficient;
private double evaluation;
private double sum;
Scanner key = new Scanner(System.in);
public Polynomial(int degree)
{
this.degree = degree;
coefficient = new int [degree+1];

}

public void setCoefficient(int coefficient, int degree)
{
this.coefficient[degree] = coefficient;
}

public int getCoefficient(int degree)
{
return coefficient[degree];
}

public void Evaluate(double value)
{
for (int i=0; i<=degree; i++)
{
System.out.println("Enter coefficent for position " + i);
this.coefficient[i] = key.nextInt();
evaluation = Math.pow(value, i)*this.coefficient[0] ;
this.sum += evaluation;

}
}
public double getSum(){
return sum;
}

public String toString()
{
String s = "";
for (int i=0; i <= degree; i++)
{
s += coefficient[i];
switch (i) {
case 0:
s += " + ";
break;
case 1:
s += "x + ";
break;
default:
s += "x^" + i + ((i==degree)?"":" + ");
}
}
return s;

}

public static void main(String[] args) {

int degree;
double sum;
int coefficient;

Scanner key = new Scanner(System.in);
System.out.println("Enter the degree of the polynomial");
degree=key.nextInt();

Polynomial fun = new Polynomial(degree);



fun.Evaluate(3.0);

System.out.println(" The sum of the polynomial is " + fun.getSum());

System.out.println(fun);

}

}

关于java - 如何打印这个类的toString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41905922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com