S
S
Senseich2019-02-09 01:22:57
Java
Senseich, 2019-02-09 01:22:57

Is it possible to view the contents of an array of objects?

I apologize in advance for the tongue-in-cheekness. I'm not familiar with java at all. I'm looking at an example of creating a simple game, and some points are not clear. As I understand it, we created an array with objects stars = new Star[40];
It's interesting to see what it is like, so that perception is easier. Is it possible to output it as something to look at?
Here is the code itself:

package com.mygdx.game;

import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;

public class Background {

    class Star {
        Vector2 position;
        float speed;

        public Star() {
            position = new Vector2((float)Math.random()*1280, (float)Math.random()*720);
            speed = 4.0f;
        }

        public void update() {
            position.x -= speed;
            if(position.x < -20) {
                position.x = 1280;
                position.y = (float)Math.random()*720;
            }
        }
    }

    Texture texture;
    Texture textureStar;
    Star[] stars;

    public Background() {
        texture = new Texture("bg.png");
        textureStar = new Texture("star12.tga");
        stars = new Star[40];
        for (int i = 0; i < stars.length; i++) {
            stars[i] = new Star();
        }
    }

    public void render(SpriteBatch batch) {
        batch.draw(texture, 0, 0);
        for (int i = 0; i < stars.length; i++) {
            batch.draw(textureStar, stars[i].position.x, stars[i].position.y);
        }
    }

    public void update() {
        for (int i = 0; i < stars.length; i++) {
            stars[i].update();

        }
    }

    public void dispose() {
        texture.dispose();
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
g0rd1, 2019-02-09
@Gordigev

You can override the toString() method of the Star class. And then call Arrays.toString(stars) in the required place (having previously imported java.util.Arrays). Example:

Sample code and result of its work
import java.util.Arrays;

public class Test {

    public static void main(String[] args) {
        Star[] stars = new Star[4];
        stars[0] = new Star(0, 0);
        stars[1] = new Star(1, 0);
        stars[2] = new Star(0, 1);
        stars[3] = new Star(1, 1);
        System.out.println(Arrays.toString(stars));
    }

    static class Star {

        int x;
        int y;

        public Star(int x, int y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public String toString() {
            return "Star{" +
                    "x=" + x +
                    ", y=" + y +
                    '}';
        }
    }

}

Результат работы кода:

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question