简体   繁体   中英

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 execute Expression and expression should execute Sum and Product maybe even number. I'm not too sure about that.

This goes to Number class Expression 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); the Sum has a constructor that has to pass the expression. I have tried many different ways after passing the operand to get it into a double but all I get is SOP.Number@566776ad. I'm not sure what to do or try next Bellow is the Sum Class.

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. 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 ).

You could write your own class which extends Number class, and override toString() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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