问题是:我有这样的代码:
public class Component {
public Component() {
// TODO Auto-generated constructor stub
}
public double[] Shifts ;
public double[][] Couplings ;
}
public class Decouplage {
public Decouplage(double[] GroupShifts, double[][] GroupCoup) {
AllComponents = new Component();
AllComponents.Shifts = GetShifts(...blah-blah-bla...);
AllComponents.Couplings = GetGouplings(...blah-blah-bla...);
}
public Component AllComponents ;
}它起作用了。但是当我尝试创建这个类组件的数组AllComponents10时
public class Decouplage {
public Decouplage(double[] GroupShifts, double[][] GroupCoup) {
AllComponents = new Component()[nComponents]; /////HOW MUST I PUT IN ONE LINE THE NUMBER OF ELEMENTS AND THE () FOR CONSTRUCTOR????
for (int iCounter=0;iCounter<nComponents;iCounter++){
AllComponents.Shifts = GetShifts(...blah-blah-bla...);
AllComponents.Couplings = GetGouplings(...blah-blah-bla...);
}
}
public Component[] AllComponents ;
}它不能编译。
但是如果我忽略构造函数的()
public class Decouplage {
public Decouplage(double[] GroupShifts, double[][] GroupCoup) {
AllComponents = new Component[nComponents]; /////IS IT LEGAL TO IGNORE CONSTRUCTOR, EVEN IF IT IS EMPTY????
for (int iCounter=0;iCounter<nComponents;iCounter++){
AllComponents.Shifts = GetShifts(...blah-blah-bla...);
AllComponents.Couplings = GetGouplings(...blah-blah-bla...);
}
}
public Component[] AllComponents ;
}它不能将移位和耦合解析为字段...
你有什么建议吗?注意: GetShifts()与标准Java的getShift()没有任何区别。这是我自己的,它工作得很好,我检查过了。
谢谢!
发布于 2010-01-20 19:38:59
这里有两个独立的概念:创建引用数组和创建类的实例。所以这一行:
AllComponents = new Component[nComponents]将创建一个Component引用数组。最初,所有引用都将为空。如果你想用对新实例的引用来填充它,你必须在该行后面加上:
for (int i = 0; i < nComponents; i++)
{
AllComponents[i] = new Component();
}编辑:回复评论,AllComponents是一个数组-它没有Shifts或Couplings的概念。如果需要为新元件设置变速或联轴器,则应使用以下任一方法:
for (int i = 0; i < nComponents; i++)
{
AllComponents[i] = new Component();
AllComponents[i].Shifts = // Code here
AllComponents[i].Couplings = // Code here
}或
for (int i = 0; i < nComponents; i++)
{
Component component = new Component();
component.Shifts = // Code here
component.Couplings = // Code here
AllComponents[i] = component;
}或者向Component的构造函数添加参数,以接受移位和耦合。
顺便说一句,我假设您是Java的新手,目前只需要关于这个特定问题的帮助-当您准备好继续前进时,研究一下Java coding conventions并更健壮地封装您的数据将是值得的。(使用公共变量通常不是一个好主意。)
发布于 2010-01-20 19:39:46
AllComponents = new Component[nComponents];
for (int iCounter=0;iCounter<nComponents;iCounter++){
AllComponents[iCounter] = new Component();
AllComponents[iCounter].Shifts = GetShifts(...blah-blah-bla...);
AllComponents[iCounter].Couplings = GetGouplings(...blah-blah-bla...);ps :变量以大写==开头是不好的做法
发布于 2010-01-20 19:43:12
尝试:
public Decouplage(double[] GroupShifts, double[][] GroupCoup) {
Component AllComponents[] = new Component[nComponents];
for (int i = 0; i < AllComponents.length; i++) {
AllComponents[i] = new Component();
AllComponents[i].Shifts = GetShifts();
AllComponents[i].Couplings = GetGouplings();
}https://stackoverflow.com/questions/2100991
复制相似问题