你能创建一个类实例数组吗?

时间:2018-02-05 02:32:31

标签: java arrays instances

是否可以创建一个类实例数组?

以下是我尝试的基本示例。专注于“生成”方法。

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

}

以下是以下是正在实例化的类的代码。

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

2 个答案:

答案 0 :(得分:2)

排序和类型声明不正确

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}

答案 1 :(得分:1)

初始化自定义数组就像使用基本类型数组一样。你在这里几乎是正确的,只有两个错误。首先,在初始化之前,无法将对象添加到数组。其次,你必须将它们存储在一个武器数组中,而不是一个字符串数组:

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