我是第二年的CS学生,并尝试修复一个简单的方法。逻辑相当容易,但不知怎的,我仍然得到一个错误,虽然我不知道这里有什么问题。
问题:
班级的开头:
private Integer dt[];
private int size;
IntManager(int k){
dt = new Integer[k];
size = 0;
}
班级内的方法:
public Integer max(){
//return largest value in dt; null if size == 0
if (size == 0) return null;
else{
Integer biggest = dt[0];//trouble here; changing to int won't help & var name also
for (int j = 0; j < size ; j++) {
if (dt[j] < biggest) biggest = dt[j];
}
}
return biggest;
}
主要课程:
IntManager num = new IntManager(100);
for (int j = 0; j < 20 ; j++) {
int x = (int)(Math.random()*10);
num.add(x);
}
num.add(57);
System.out.println(num);
System.out.println(num.found(5));//Ignore this
System.out.println(num.max());
答案 0 :(得分:2)
您的最大变量是在ifelse范围内定义的,因此在该细分受众群之外是不可见的 将Integer声明为一个孔方法变量......
public Integer max(){
Integer biggest=null;
if (size != 0) {
Integer biggest = dt[0];
for (int j = 0; j < size ; j++) {
if (dt[j] < biggest) biggest = dt[j];
}
}
return biggest;
}
答案 1 :(得分:1)
问题在于你的块
public Integer max(){
//return largest value in dt; null if size == 0
if (size == 0) return null;
else{
Integer biggest = dt[0];//trouble here; changing to int won't help & var name also
for (int j = 0; j < size ; j++) {
if (dt[j] < biggest) biggest = dt[j];
}
}
return biggest;
}
您在该else块的范围内声明最大值,因此当您到达return语句时它不可见。要纠正它,你应该有类似的东西:
public Integer max(){
//return largest value in dt; null if size == 0
Integer biggest = dt[0]
if (size == 0) return null;
else{
;//trouble here; changing to int won't help & var name also
for (int j = 0; j < size ; j++) {
if (dt[j] < biggest) biggest = dt[j];
}
}
return biggest;
}