有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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] + " ");
        }   
    }

共 (2) 个答案

  1. # 1 楼答案

    行号没有显示出来,但是我已经把代码读了几遍,发现了一些bug。 首先,私有变量a应该声明为长数组,而不仅仅是长数组。原因是,稍后将初始化为数组,但之前将其定义为长数组

            private long a[];
    

    find()函数的返回类型应为long not int

    public long find(long searchKey) {
            
            for(int i=0; i < nElems; i++)
                if(searchKey == a[i])
                    return a[i];
    }
    

    另外,如果您在下面的行中遇到某种逻辑错误,我也不会感到惊讶

    temp[o++] = a[i];
    

    最好是这样分两步递增

    temp[o]  = a[1];
    o++;
    

    原因是您跳过了索引0,直接转到了索引1

  2. # 2 楼答案

    • a的声明修复为
         private long[] a;
      

    另外:

    • 您需要将find的返回类型更改为long,并添加默认的返回语句,例如:

      public long find(long searchKey) {
      
          for (int i = 0; i < nElems; i++)
              if (searchKey == a[i])
                  return a[i];
          return -1;
      }
      
    • 关闭Scanner资源sc.close();