【问题标题】:Sort an Array using Bubble sort, Error- required: variable, found: value使用冒泡排序对数组进行排序,需要错误:变量,找到:值
【发布时间】:2014-01-07 17:34:12
【问题描述】:

我正在尝试使用 冒泡排序 对数组进行排序,但它不起作用。它说'必需:变量,找到:值'

Array.java:143:错误:意外类型
temp.get(d) = temp.get(d+1);

^

必填:变量
找到:值


Array.java:144:错误:意外类型
temp.get(d+1) = 交换;

^

必需:变量
找到:值



所以给出了Main,我需要做的就是编写这个冒泡排序函数


这是我写的

public static void bubbleSort(Array<Integer> lista){
boolean swapped;
    Array<Integer> temp;
    int n;

    n= temp.size;

    int swap;

     for (int c = 0; c < ( n - 1 ); c++) {
        for (int d = 0; d < n - c - 1; d++) {
            if (temp.get(d) > temp.get(d+1))
            {
                swap = temp.get(d);
                temp.get(d) = temp.get(d+1);
                temp.get(d+1) = swap;
            }
        }
     }
}



这是给出的主要内容

public static void main(String[] args) throws IOException{
    BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); 
    String s = stdin.readLine();
    int N = Integer.parseInt(s);
    Array<Integer> niza =new Array<Integer>(N);
    bubbleSort(niza);

    for(int i=0;i<N;i++){
        s = stdin.readLine();
        niza.set(i, Integer.parseInt(s));
    }

    System.out.println(brojDoProsek(niza));
}


如何解决此错误?

【问题讨论】:

  • 您不能分配给函数。你正在寻找set()

标签: java arrays sorting bubble-sort


【解决方案1】:

假设 Array 实际上是 ArrayList,并假设您要将索引 d + 1 处的值存储在索引 d 中,您需要

temp.set(d, temp.get(d + 1));

temp.get(d) 不是可以赋值的变量。它是一个返回值的表达式。而且您不能将任何内容分配给值。

【讨论】:

  • 现在 n = temp.size 有问题;它说 Array.java:134: error: variable temp might not have been initialized n= temp.size;
  • 收到此错误是件好事:您确实没有初始化 temp。去做吧。
【解决方案2】:

正如其他用户所说,您必须使用set() 方法来更改存储在数组索引处的值。

我认为您的意思是使用 ArrayList。如果是这种情况,那么您应该使用n = temp.size() 而不是n = temp.size 来获取列表的长度,因为size 是ArrayList 类中的一个方法。

【讨论】:

    猜你喜欢
    • 2020-07-17
    • 2020-05-17
    • 2016-07-25
    • 2018-09-22
    • 2019-05-10
    • 2017-09-27
    • 2019-04-14
    • 2017-05-29
    • 2017-01-24
    相关资源
    最近更新 更多