我正在研究一个问题,我需要一个由布尔数组表示的类。这是我唯一的构造函数。
private boolean[] integerSet;
private static final int ARRAY_LENGTH = 101; // set will always be 0-100
// no argument constructor
// creates set filled with default value false
public Exercise_8_13()
{
integerSet = new boolean[ARRAY_LENGTH];
}
我在此之后编写的方法都给出了错误“表达式的类型必须是数组类型,但它已解析为Exercise_8_13”。这些方法采用Exercise_8_13类型的参数。
我是否需要制作另一种类型的构造函数来防止错误?或者它是我的构造函数中的东西?该问题仅指明必须创建无参数构造函数。
我看过这个似乎是类似问题的问题,但我仍然不理解解决方案。 The type of an expression must be an array type, but it is resolved to Object
这是一个示例方法,在[counter],b [counter]和intersectionSet [counter]的两个实例上触发错误。
public static void intersection(Exercise_8_13 a, Exercise_8_13 b)
{
Exercise_8_13 intersectionSet = new Exercise_8_13();
for (int counter = 0; counter < ARRAY_LENGTH; counter++)
{
if ((a[counter] = false) || (b[counter = false]))
{
intersectionSet[counter] = false;
}
else
{
intersectionSet[counter] = true;
}
}
}
答案 0 :(得分:2)
即使a
的类型为boolean
,但a[counter]
类型不属a
,您也会将Exercise_8_13
视为boolean[]
数组b
}}。您对intersectionSet
和integerSet[counter]
也一样。
您想在a
中查看a[counter]
,因此请将a.integerSet[counter]
更改为b[counter]
。
对intersectionSet[counter]
和{{1}}执行相同操作。
答案 1 :(得分:0)
我不清楚为什么你会收到错误,但我试图运行我的代码版本,它工作正常。首先,构造函数仅在创建类的实例时运行。因此,如果在main方法中创建相同的实例并检查数组的长度。这是运行良好的代码。
public class Exercise_8_13{
private static boolean[] integerSet ;
private static final int ARRAY_LENGTH = 101;
public Exercise_8_13()
{
integerSet =new boolean[ARRAY_LENGTH];
}
public static void main(String args[])
{
Exercise_8_13 z = new Exercise_8_13();//new instance being created
if(integerSet!=null)
{
System.out.println("Success " +integerSet.length);
}
}
}
答案 2 :(得分:0)
你的构造函数很好。您的错误表示预期类型与您尝试接受或返回其中一种方法之间的不匹配。如果您共享其中一种呈现错误条件的方法,则很容易发现。
例如,如果你有一个看起来像这个的方法,那么你的编译器将识别所述返回类型(Exercise_8_13)和实际返回类型(boolean [])之间的不匹配。
public Exercise_8_13 copy() {
return this.integerSet; // deliberate bug
}