Reputation: 5
Is it possible to make an array of class instances?
Below is a basic example of my attempt. Focus on method "Generate".
import java.util.Scanner;
public class Main {
public static Scanner Scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("What is your name?");
String name = Scan.nextLine();
Player player1 = new Player(name);
player1.getStats();
}
public static void generate() {
String[] weaponShopInv = {rustySword, ironSword, sharpSword}
Weapon rustySword = new Weapon("Rusty Sword","Melee","Short Sword", 5, 30);
Weapon ironSword = new Weapon("Iron Sword","Melee","Short Sword", 10, 100);
Weapon sharpIronSword = new Weapon("Sharp Iron Sword","Melee","Short Sword", 15, 250);
}
}
And just in case, below is the code for the class which is being instantiated.
public class Weapon {
String name;
String type;
String style;
int damage;
int price;
public Weapon(String e, String a, String b, int c, int d) {
type = a;
style = b;
damage = c;
price = d;
name = e;
}
}
Upvotes: 0
Views: 60
Reputation: 44854
The ordering and type declaration is not correct
Weapon rustySword = new Weapon("Rusty Sword","Melee","Short Sword", 5, 30);
Weapon ironSword = new Weapon("Iron Sword","Melee","Short Sword", 10, 100);
Weapon sharpIronSword = new Weapon("Sharp Iron Sword","Melee","Short Sword", 15, 250);
Weapon[] weaponShopInv = {rustySword, ironSword, sharpSword}
Upvotes: 2
Reputation: 3430
Initializing custom arrays are just like doing so with primitive type arrays. You are almost correct here, only two mistakes. First, you cannot add an object to an array before it is initialized. Secondly, you must store them in a weapons array, not a string array:
Weapon rustySword = new Weapon("Rusty Sword","Melee","Short Sword", 5, 30);
Weapon ironSword = new Weapon("Iron Sword","Melee","Short Sword", 10, 100);
Weapon sharpIronSword = new Weapon("Sharp Iron Sword","Melee","Short Sword", 15, 250);
Weapon[] weaponShopInv = {rustySword, ironSword, sharpSword};
Upvotes: 1