Category: 3D computer graphics software
Category: 3D rendering software for Linux
Category: Computer-aided design software
Category: Desktop 3D graphics software
Category: Engineering software
Category: Product lifecycle management
Category: Product design software
Category: Product management software
Category: Product modeling software
Category: Product team software
Category: Product lifecycle management software
Category: 3D animation software
Category: 3D graphics software
Category: 3D web
Category: 3D graphics software for Linux
Category: Free and open-source software
Category: Open-source 3D graphics software
Category: Computer-aided design software for Windows
Category: 3D modeling softwareQ:
How can I store an array of objects in an arraylist?
I'm creating a simple RPG game using Java. I have a class called "Character" with three attributes - name, level, and health. I have created an arraylist to store them all in.
I'm trying to store all of the characters in my arraylist so that I can iterate through them to create a print-screen of the game. My current code is:
public ArrayList characters = new ArrayList();
public void create(){
Character John = new Character("John", 1, 5);
characters.add(John);
}
public void createCharacter(){
for (Character character : characters){
System.out.println(character.getName() + " (" + character.getLevel() + ") has " + character.getHealth() + " health!");
}
}
But my print-screen prints out:
John (1) has 5 health!
I'm trying to understand why it is printing out the health instead of the character. Could someone explain it to me?
A:
In the line
System.out.println(character.getName() + " (" + character.getLevel() + ") has " + character.getHealth() + " health!");
you are actually using the toString() method of the Character class. If you wanted to print a String that represents the object, you would have to call toString() on the object to do that. If you want to display the class of the object, you would be359ba680
Related links:
Comments