簡體   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