繁体   English   中英

我的toString函数被调用而没有调用它

[英]my toString function is called without calling it

我是Java的新手,我正在制作此程序,该程序将机器人随机放置在预定义的舞台上。

发生这种情况时,我正在主要测试我的addRobot方法 在此处输入图片说明

这是我的两个类的代码:

import java.util.Scanner;
import java.util.Random;



public class RobotArena {

    private int xmax,ymax;
    Robot ro;
    RobotArena roaa;
    public static Robot rrr[];
    RobotArena (int xs, int ys, Random r){
        xmax = xs;
        ymax = ys;
        ro = new Robot(r.nextInt(xmax), r.nextInt(ymax), this); 
    }

    public void addRobot () {

    Scanner add = new Scanner(System.in); 
    System.out.print("How many robots would you like to add?");


    int numberofRobots = add.nextInt();
    rrr = new Robot[numberofRobots];
    add.close();

    for(int c=0 ;c < numberofRobots ; c++)
    {
        Random addro2 = new Random();
        int Xcoordinate = addro2.nextInt(xmax);
        int Ycoordinate = addro2.nextInt(ymax);
        rrr[c]= new Robot(Xcoordinate,Ycoordinate, null);
        System.out.println( rrr[c]);
    }

    }

import java.util.Random;

public class Robot {

    private int x, y, dx, dy, ID;
    private static int RobotID;
    private  RobotArena roA;


    Robot(){
        this(0,0, null);

    }

    Robot(int sx, int sy, RobotArena ra){
        x = sx;
        y = sy;
        dx = 1;
        dy = 1;
        roA = ra;
        ID = RobotID;
        RobotID++;


    }

    public String toString() {
        return "Robot ID = " + ID +", robot is at " + x + ", " + y;
    }

    public boolean isHere(int ix, int iy) {
            if (ix == x && iy == y) {
                return true;
            }
            else 
            {
                return false;
            }
    }


    public static void main(String[] args) {

        RobotArena rrr1;
        Random addro = new Random();
        rrr1 = new RobotArena(20, 5, addro);
        rrr1.addRobot();
        }

}

即使我从未调用过toString函数,该函数都会为竞技场中每个机器人的ID和位置生成一个字符串,

它被间接称为。 您调用System.out.println(rrr[c]); 并实现该方法,以使其打印给定参数的argument.toString()

让我们看一下最近的实现8u40-b25 )。 System.out指向类型为PrintStream的对象,这是其println方法的实现方式:

 public void println(Object x) {
     String s = String.valueOf(x);
     synchronized (this) {
         print(s);
         newLine();
     }
 }

它调用String.valueOf(x)实现 ):

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

在参数上调用obj.toString()

这是因为在Java中-如果您打印对象-toString方法将隐式调用

如果您这样做:

System.out.println( rrr[c]);

那么println方法会在内部为您调用toString……这就是该行为的真正解释。

暂无
暂无

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

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