这似乎是一个非常简单的问题,但我不确定我是否正确使用这些构造函数。如果你可以看看并告诉我为什么当我尝试打印这些数据时,它会显示(我假设是)数据位置。我无法想办法打印出名称,冰点,沸点和单位数量。任何有关提高效率的建议也是受欢迎的。
这是第一堂课
public class ChemicalInventory {
public static void main(String[] args) {
listInventory();
}
public static void listInventory(){
Chemical Ethanol = new Chemical("Ethanol", "-173", "172", "1575");
Chemical Oxygen = new Chemical("Oxygen", "-363", "-306", "1000");
Chemical Water = new Chemical("Water", "32", "212", "5000");
Chemical Benzene = new Chemical("Benzene", "41.9", "176.2", "2750");
Chemical EthyleneGlycol = new Chemical("Ethylene Glycol", "8.78", "378", "1900");
System.out.println("Current Chemical Inventory: ");
System.out.println(Ethanol);
System.out.println(Oxygen);
System.out.println(Water);
System.out.println(Benzene);
System.out.println(EthyleneGlycol);
}
}
这是第二节课。
public class Chemical {
private String chemName;
private String chemFreezingPoint;
private String chemBoilingPoint;
private String chemUnitNumbers;
public Chemical(String name, String freezingPoint, String boilingPoint, String unitNumbers){
chemName = name;
chemFreezingPoint = freezingPoint;
chemBoilingPoint = boilingPoint;
chemUnitNumbers = unitNumbers;
}
//String[][] chemArray = new String [5][4];
String[][] chemArray = {{"Ethanol","-173","172","1575"},{"Oxygen","-363","-306","1000"},{"Water","32","212","5000"},
{"Benzene","41.9","176.2","2750"},{"Ethylene Glycol","8.78","378","1900"}};
}
这是我运行程序时得到的结果:
Current Chemical Inventory:
Chemical@15db9742
Chemical@6d06d69c
Chemical@7852e922
Chemical@4e25154f
Chemical@70dea4e
答案 0 :(得分:1)
因为您当前正在打印对象的引用。 尝试这样的事情:
System.out.println(Ethanol.toString());
这应该为您提供Object内的数据。
此外,您可以覆盖toString()方法并编写自己的实现。
这样的事情:
public class Chemical {
private String chemName;
private String chemFreezingPoint;
private String chemBoilingPoint;
private String chemUnitNumbers;
public Chemical(String name, String freezingPoint, String boilingPoint, String unitNumbers){
chemName = name;
chemFreezingPoint = freezingPoint;
chemBoilingPoint = boilingPoint;
chemUnitNumbers = unitNumbers;
}
//String[][] chemArray = new String [5][4];
String[][] chemArray = {{"Ethanol","-173","172","1575"},{"Oxygen","-363","-306","1000"},{"Water","32","212","5000"},
{"Benzene","41.9","176.2","2750"},{"Ethylene Glycol","8.78","378","1900"}};
public String toString(){
return // Return the string in the format you want here...
}
}
答案 1 :(得分:0)
您需要覆盖toString()方法,如下所示:
@Override
public String toString() {
return "Chemical [chemName=" + chemName + ", chemFreezingPoint=" + chemFreezingPoint + ", chemBoilingPoint="
+ chemBoilingPoint + ", chemUnitNumbers=" + chemUnitNumbers + "]";
}
您可以随意格式化return语句。
你的构造函数没有问题,绝对没问题。
答案 2 :(得分:0)
你的建造者很好。实际上这里什么都没有打破。在java中,每个类都有一个默认的toString()方法,它打印出来,以及你在那里看到的内容。你可以免费获得,但它的信息量不大。
尝试将此添加到您的化学类:
public String toString(){
return "I am a chemical:" + name;
}
并根据需要进行扩展。