简体   繁体   English

这会打印出 SOP.Number@566776ad 无法弄清楚如何让它只打印出值

[英]This prints out SOP.Number@566776ad can't figure out how to make it just print out the value

This is supposed to have a Processor, Expression, Sum, Number and Product class.这应该有一个 Processor、Expression、Sum、Number 和 Product 类。 Processor execute Expression and expression should execute Sum and Product maybe even number.处理器执行表达式和表达式应该执行 Sum 和 Product 可能是偶数。 I'm not too sure about that.我不太确定。

This goes to Number class Expression e1 = new Number(2.0);这转到 Number 类表达式 e1 = new Number(2.0);

        public Number(double operand) {
        Double code = new Double(operand);
           code.toString();
            System.out.println("double : " + code);
           return;

This passes fine.这通过得很好。 I get the number我得到了号码

public class TestSOP  {
public static void main(String[] args) {
    Processor proc = new Processor();
    Expression e1 = new Number(2.0);
    Expression e2 = new Number(3.1);
    Expression e3 = new Number(-5.0);
    Sum s1 = new Sum(e1, e2, e3);
    System.out.println("s1 - " + proc.execute(s1));
    Product p1 = new Product(s1, e3);
    System.out.println("s1 - " + proc.execute(s1));
    // etc.
}

} }

The problem is this line Sum s1 = new Sum(e1, e2, e3);问题是这一行 Sum s1 = new Sum(e1, e2, e3); the Sum has a constructor that has to pass the expression. Sum 有一个必须传递表达式的构造函数。 I have tried many different ways after passing the operand to get it into a double but all I get is SOP.Number@566776ad.在将操作数传递给双精度数后,我尝试了许多不同的方法,但我得到的只是 SOP.Number@566776ad。 I'm not sure what to do or try next Bellow is the Sum Class.我不知道接下来该做什么或尝试什么 贝娄是 Sum 类。

public  class Sum implements Expression   { 
 public Sum(Expression ...operand ) {
SOP.Number.Numbers(operand); }

Firstly, System.out.println() calls passed in object's toString() function to convert the object to a string representation, so you don't need to convert it beforehand.首先,System.out.println() 调用传入对象的toString() 函数将对象转换为字符串表示,因此您无需事先将其转换。 Also, if you do so, you would need to assign it to a variable:此外,如果你这样做,你需要将它分配给一个变量:

String printCode = code.toString(); // redundant
System.out.println("double : " + printCode);

Double overrides toString() method (see https://docs.oracle.com/javase/8/docs/api/?java/lang/Double.html ), hence your number is printed, while Number only inherits it from Object class (seehttps://docs.oracle.com/javase/8/docs/api/java/lang/Number.html ).双重覆盖 toString() 方法(参见https://docs.oracle.com/javase/8/docs/api/?java/lang/Double.html ),因此您的号码被打印出来,而 Number 仅从 Object 类继承它(参见https://docs.oracle.com/javase/8/docs/api/java/lang/Number.html )。

You could write your own class which extends Number class, and override toString() method.您可以编写自己的类来扩展 Number 类,并覆盖 toString() 方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM