java I持续不断地出现一种错误类型:“表达式的类型必须是数组类型,但解析为long”
每当我引用长数组“a”(即第21、22、28、36、38、46、49、60行)时,我总是会遇到这个错误。我是Java的初学者,真的不理解错误消息。即使对数组进行类型转换也不起作用
错误:表达式的类型必须是数组类型,但解析为long
import java.util.*;
public class MyLongArray
{
private long a;
private int nElems;
public MyLongArray(int size)
{
Scanner sc= new Scanner(System.in);
long[] a = new long[size];
for(int i=0; i < nElems; i++)
a[i] = sc.nextLong();
nElems = a.length;
}
public int find(long searchKey) {
for(int i=0; i < nElems; i++)
if(searchKey == a[i])
return a[i];
}
public void insert(long value) {
}
public long getElem(int index) {
return a[index];
}
public boolean delete(long value) {
long[] temp = new long[nElems];
int f = 0;
int o = 0;
for(int i=0; i < nElems; i++)
{
if(value != a[i])
{
temp[o++] = a[i];
}
else
f = 1;
}
for(int j=0; j < nElems; j++)
a[j] = temp[j];
for(int i=0; i < nElems; i++)
System.out.print(a[i] + " ");
if (f==1)
return true;
else
return false;
}
public void display()
{
for(int i =0; i < nElems; i++)
System.out.print(a[i] + " ");
}
}
# 1 楼答案
行号没有显示出来,但是我已经把代码读了几遍,发现了一些bug。 首先,私有变量a应该声明为长数组,而不仅仅是长数组。原因是,稍后将初始化为数组,但之前将其定义为长数组
find()函数的返回类型应为long not int
另外,如果您在下面的行中遇到某种逻辑错误,我也不会感到惊讶
最好是这样分两步递增
原因是您跳过了索引0,直接转到了索引1
# 2 楼答案
a
的声明修复为另外:
您需要将
find
的返回类型更改为long
,并添加默认的返回语句,例如:关闭
Scanner
资源sc.close();