如何打印出这个类的toString?

时间:2017-01-28 03:04:06

标签: java class

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

set.seed(123)
df.wide  = data.frame(
  X = 100:105, 
  Thing_1 = cumsum(rnorm(6,10,3)), 
  Thing_2 = cumsum(rnorm(6,6,2)),
  Thing_3 = cumsum(rnorm(6,3,1)))

df.wide$T1 = df.wide$Thing_1
df.wide$T2 = df.wide$Thing_1 + df.wide$Thing_2
df.wide$T3 = df.wide$T2 + df.wide$Thing_3

  plot_ly(df.wide, fill = 'tozeroy', line = list(color = '#00000000')) %>% 
    add_trace(x = ~X, y = ~T3, name = 'Thing 3', 
              type = 'scatter', mode = 'lines',  fillcolor = 'green') %>% 
    add_trace(x = ~X, y = ~T2, name = 'Thing 2', 
              type = 'scatter', mode = 'lines',  fill = 'tozeroy', fillcolor = 'blue') %>% 
    add_trace(x = ~X, y = ~T1, name = 'Thing 1', 
              type = 'scatter', mode = 'lines',  fill = 'tozeroy', fillcolor = 'orange') 

3 个答案:

答案 0 :(得分:1)

这应该是你应该继续的。为简单起见,我在main类中包含了Polynomial函数,因此如果要将其保留在测试类中,则必须对其进行修改。请注意,degree已经变成了一个大小为degree +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);

}

}

答案 1 :(得分:1)

使类的对象可打印的常用方法是在类中提供toString方法,该方法指定如何将该类的对象表示为String。诸如println之类的方法以及输出值的其他方法如果需要打印该类的对象,则会调用类的toString方法。

您应该对Polynomial类使用相同的模式 - 使用所有输出逻辑编写toString方法。然后在你的PolynomialTester课程中,你需要写的只是System.out.println(fun);,剩下的就会发生。您会发现这比编写实际执行打印的方法更具通用性。例如,您可以编写类似

的内容
System.out.println("My polynomial is " + fun + " and " + fun + " is my polynomial.");

如果那是你的乐趣。

其他一些事情让我担心你的课程。

  • 您似乎只存储一个系数和一个指数。我期望多项式具有整个系数阵列。
  • 您有evaluationsum的字段 - 但这些仅在评估多项式时才有意义。它们不是多项式的长期属性。所以不要将它们存放在田地里。将它们作为evaluate方法的局部变量,并返回评估结果。
  • 我希望像这样的课程是不可改变的。也就是说,您应该在创建对象时提供所有系数,然后再也不要更改它们。如果你这样做,就没有必要编写setter方法。

因此,我编写了我自己的课程版本,修复了上面列出的问题,并实现了可用于打印它的toString方法。第二版toString可让您指定要用于x的字母。我已经使用了&#34; varargs&#34;在构造函数中,您可以使用诸如

之类的行构造多项式
Polynomial fun = new Polynomial (7, 2, 5, 0, 1);  

从常数项到具有最高指数的项的系数指定系数。或者你可以传递一个数组。

看到我已经改变了逻辑 - 我的版本以常规顺序打印多项式,从最高到最低指数。如果系数是整数,则不包括小数。它不会在x前打印1。并且它与-符号完全一致。

import java.util.Arrays;

public class Polynomial {

    private double[] coefficients;

    public Polynomial(double... coefficients) {
        this.coefficients = Arrays.copyOf(coefficients, coefficients.length);
    }

    public int getDegree() {
        int biggestExponent = coefficients.length - 1;
        while(biggestExponent > 0 && coefficients[biggestExponent] == 0.0) {
            biggestExponent--;
        }
        return biggestExponent;
    }

    public double getCoefficient(int exponent) {
        if (exponent < 0 || exponent > getDegree()) {
            return 0.0;
        } else {
            return coefficients[exponent];
        }
    }

    public double evaluateAt(double x) {
        double toReturn = 0.0;
        for (int term = 0; term < coefficients.length; term++) {
            toReturn += coefficients[term] * Math.pow(x, term);
        }
        return toReturn;
    }

    @Override
    public String toString() {
        return toString('x');
    }

    public String toString(char variable) {

        boolean anythingAppendedYet = false;
        StringBuilder toReturn = new StringBuilder();

        for (int exponent = coefficients.length - 1; exponent >= 0; exponent--) {
            if (coefficients[exponent] != 0.0) {
                appendSign(toReturn, exponent, anythingAppendedYet);
                appendNumberPart(toReturn, exponent);
                appendLetterAndExponent(toReturn, exponent, variable);
                anythingAppendedYet = true;
            }
        }

        if (anythingAppendedYet) {
            return toReturn.toString();
        } else {
            return "0";
        }
    }

    private void appendSign(StringBuilder toAppendTo, int exponent, boolean anythingAppendedYet) {
        if (coefficients[exponent] < 0) {
            toAppendTo.append(" - ");
        } else if (anythingAppendedYet) {
            toAppendTo.append(" + ");
        }
    }

    private void appendNumberPart(StringBuilder toAppendTo, int exponent) {
        double numberPart = Math.abs(coefficients[exponent]);
        if (numberPart != 1.0 || exponent == 0) {
            //Don't print 1 in front of the letter, but do print 1 if it's the constant term.
            if (numberPart == Math.rint(numberPart)) {
                // Coefficient is an integer, so don't show decimals
                toAppendTo.append((long) numberPart);
            } else {
                toAppendTo.append(numberPart);
            }
        }
    }

    private void appendLetterAndExponent(StringBuilder toAppendTo, int exponent, char variable) {
        if (exponent > 0) {
            toAppendTo.append(variable);
        }

        if (exponent > 1) {
            toAppendTo.append("^");
            toAppendTo.append(exponent);
        }
    }
}  

所以我用这个类测试了它

public class PolynomialTester {
    public static void main(String[] args) {
        Polynomial fun = new Polynomial (7, 2, 5, 0, 1);
        System.out.println(fun.getDegree());
        System.out.println(fun.evaluateAt(3));
        System.out.println(fun);
    }
}

,输出

4
139.0
x^4 + 5x^2 + 2x + 7

然后我意识到你希望能够在循环中输入系数。所以我将PolynomialTester更改为此。看看我如何构建数组,然后创建对象。

import java.util.Scanner;

public class PolynomialTester {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter the degree:");
        int degree = input.nextInt();

        double[] coefficients = new double[degree + 1];
        for( int exponent = 0; exponent <= degree; exponent++) {
            System.out.println("Enter the coefficient of x^" + exponent);
            coefficients[exponent] = input.nextDouble();
        }
        Polynomial fun = new Polynomial (coefficients);
        System.out.println(fun.evaluateAt(3));
        System.out.println(fun);
        input.close();
    }
}

请注意,如果您确实希望您的多项式打印在&#34;反向&#34;顺序,首先使用常量项,您可以将toString方法中的循环更改为此。

for (int exponent = 0; exponent < coefficients.length; exponent++) {

答案 2 :(得分:0)

您可以添加一个类成员String poly,然后修改以下方法。

public void Evaluate(double value)
{
    for (int i=0; i<=degree; i++)
    {
        System.out.println("Enter coefficent for position " + i);
        this.coefficient= key.nextInt();
        evaluation = Math.pow(value, i)*coefficient ;
        this.sum += evaluation;
        this.poly = "";
        if(coefficient != 0)
        {
            if(i > 0)
            {
                this.poly += " + " + Integer.toString(coefficient) + "x^" + Integer.toString(i); // you may replace x with the actual value if you want
            }
            else
            {
                this.poly = Integer.toString(coefficient)
            }
        }
     }
}