【发布时间】:2021-12-15 00:37:08
【问题描述】:
关于堆栈溢出的第一个问题! 我觉得这个必须是 Java 初学者的常见问题。但我已经尝试了几个小时,但一直无法找到解决方案。我认为对象属性可以通过这种方式访问。
一开始我以为weapon[0]实际上是一个对象数组,所以当我创建对象数组Inventory[] inventory时,我在构造函数中使用了一个对象数组。我立即解决了这个问题,但这个问题仍然存在。
这更令人讨厌,因为在调试模式下,我可以从字面上看到weapon[0] 内部的Inventory[] inventory 及其属性。
Look at Eclipse mock me.
我目前的理论是,将对象weapon[0](类Weapons 的实例)放在对象数组Inventory[] inventory 中可能是问题所在,并且由于该位置,无法以某种方式访问对象的属性。任何帮助将不胜感激,谢谢!这是我第一次搞乱数组,所以我绝对是个新手。关于我的格式等的任何提示也将非常有帮助!
package arraytest;
import java.util.Scanner;
import java.util.InputMismatchException;
import java.lang.NumberFormatException;
public class ArrayTest {
static Scanner kb = new Scanner(System.in);
static int i = 0;
static int choice = 0;
public static void main(String[] args) {
Weapons[] weapon = new Weapons[3];
weapon[0] = new Weapons(0,"Wooden Sword",1,2);
weapon[1] = new Weapons(1,"Bronze Sword",2.5,7.5);
weapon[2] = new Weapons(2,"Iron Sword",5,10);
Armor[] armor = new Armor[3];
armor[0] = new Armor(3,"Wooden Armor",2,5);
armor[1] = new Armor(4,"Bronze Armor",3,10);
armor[2] = new Armor(5,"Iron Armor",5,15);
Enemy[] enemy = new Enemy[3];
enemy[0] = new Enemy(0,"Skeleton",3,0,10);
enemy[1] = new Enemy(1,"Goblin",2,1,5);
enemy[2] = new Enemy(2,"Zombie",4,1,8);
Inventory[] inventory = new Inventory[256];
String chooseweapon = String.format(
"Choose your weapon:\n"
+ "1. %s\n"
+ "2. %s\n"
+ "3. %s\n"
,
weapon[0].name,
weapon[1].name,
weapon[2].name
);
System.out.print(chooseweapon);
while (i==0) {
i++; //1
try {
choice = Integer.parseInt(kb.nextLine());
} catch (NumberFormatException e) {
System.out.println("Error. Try again.");
i--; //0
continue;
}
if (choice < 1 || choice > 3) {
System.out.println("Error. Try again.");
i--; //0
}
}
if (choice == 1) {
inventory[0] = new Inventory(weapon[0]);
}
System.out.println(inventory[0].item); //this is the problem here. i can't put .item.name, error is "name cannot be resolved or is not a field"
}
}
class Inventory {
public Object item;
Inventory(Object item) {
this.item = item;
}
}
class Armor {
public int id;
public String name;
public double defnum;
public double val;
Armor(int id, String name, double defnum, double val) {
this.id = id;
this.name = name;
this.defnum = defnum;
this.val = val;
}
}
class Weapons {
public int id;
public String name;
public double attdmg;
public double val;
Weapons(int id, String name, double attdmg, double val) {
this.id = id;
this.name = name;
this.attdmg = attdmg;
this.val = val;
}
}
class Enemy {
public int id;
public String name;
public double attdmg;
public double defnum;
public double health;
Enemy(int id, String name, double attdmg, double defnum, double health) {
this.id = id;
this.name = name;
this.attdmg = attdmg;
this.defnum = defnum;
this.health = health;
}
}
【问题讨论】:
-
您的实例变量
item的类型为Object,而该类型根本没有name字段。因此,您可以专门化类型或将表达式inventory[0].item转换为Weapon。
标签: java arrays object attributes