javaarraysinstances

Can you make an array of class instances?


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;
    }
}

Solution

  • 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}