简体   繁体   中英

java. required: variable , found: value error

when I run this code on a HankerRank problem, I get an error about variables and values. I have googled about that, unfortunately still can't figure out the reason. Would you please explain about this error?

public static void minimumBribes(List<Integer> q) {
    // Write your code here
    
        int swap =0;
        for(int i=q.size()-1; i>=0; i--){
            if(q.get(i) != i+1){
                if(i-1>=0 && q.get(i-1) == i+1){
                    int temp = q.get(i);
                    q.get(i) = q.get(i-1);
                    q.get(i-1) = temp;
                    swap++;
                } else if( i-2 >= 0 && q.get(i-2) == i+1){
                    int temp2 = q.get(i-2);
                    q.get(i-2) = q.get(i);
                    q.get(i) = temp2;
                    swap+=2;
                 } else {
                     System.out.println("Too chaotic");
                 }
            }
        }
        System.out.println(swap);
    }

Solution.java:29: error: unexpected type
                    q.get(i) = q.get(i-1);
                         ^
  required: variable
  found:    value
Solution.java:30: error: unexpected type
                    q.get(i-1) = temp;
                         ^
  required: variable
  found:    value
Solution.java:34: error: unexpected type
                    q.get(i-2) = q.get(i);
                         ^
  required: variable
  found:    value
Solution.java:35: error: unexpected type
                    q.get(i) = temp2;
                         ^
  required: variable
  found:    value
4 errors

You are trying to set the get() returned value which is not a variable. use q.set() :

public static void minimumBribes(List<Integer> q) {
    // Write your code here
    
        int swap =0;
        for(int i=q.size()-1; i>=0; i--){
            if(q.get(i) != i+1){
                if(i-1>=0 && q.get(i-1) == i+1){
                    int temp = q.get(i);
                    q.set(i,i-1);
                    q.set(i-1,temp);
                    swap++;
                } else if( i-2 >= 0 && q.get(i-2) == i+1){
                    int temp2 = q.get(i-2);
                    q.set(i-2,i);
                    q.set(i,temp2);
                    swap+=2;
                 } else {
                     System.out.println("Too chaotic");
                 }
            }
        }
        System.out.println(swap);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM