简体   繁体   中英

ArrayList.add not working

l1 and l2 are arrays that I input. I want to merge l1 and l2 into l3 and sort them in ascending order. When i tried to add l1 and l2 into l3 i get a syntax error stating, "The left-hand side of an assignment must be a variable".

import java.util.ArrayList;
import java.util.Scanner;

public class Array {

    public static void main(String[] args) {

        String david;
        String bert;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a list of integers: ");
        bert = input.next();
        System.out.println("Enter a second list of integers: ");
        david = input.next();

        String parts[] = bert.split(" ");
        String parts2[] = david.split(" ");
        int[] l1 = new int[parts.length];
        for(int n = 0; n < parts.length; n++) {
           l1[n] = Integer.parseInt(parts[n]);
        }
        int[] l2 = new int[parts2.length];
        for(int n = 0; n < parts2.length; n++) {
           l2[n] = Integer.parseInt(parts2[n]);
        }

        int w = 0;
        int s = 0;
        int a = 0;
        ArrayList<Integer> l3 = new ArrayList <Integer> ();

        while(w>s)
        if (l1[w]<=l2[s])
            l3.add(a++) = l1[w++];
        else 
            l3.add(a++) = l2[s++];

        while(w>s)
        if (l1[w]<=l2[s])
                l3.add(a++) = l1[w++];
        else 
                l3.add(a++) = l2[s++];

        while(w==s)
        if (l1[w]<=l2[s])
                l3.add(a++) = l1[w++];
        else 
                l3.add(a++) = l2[s++];

        for (int i = 0; i < l3.size(); i++) {
              System.out.print(l3.add(i) + " ");
            }

     }      
}

The ArrayList.add(int, E) method can take an index and a value (that is, you can't assign the value to the result of add or the left-hand side of an assignment must be a variable ). Also, please use braces. Something like

while (w > s) {
    if (l1[w] <= l2[s]) {
        l3.add(a++, l1[w++]);
    } else {
        l3.add(a++, l2[s++]);
    }
}

You are trying to do a .add() method at the same time as assigning it to another variable. This doesn't work. You should stick with just:

l3.add(a++);

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