0

I'm a beginner at java. I want to be able to swap elements using index value while using my own method or without using collections.swap

import java.util.LinkedList;
import java.util.Scanner;

class Main {
    private static LinkedList<Integer> llist;
  public static void main(String[] args) {
    LinkedList<Integer> languages = new llist<>();
    Scanner s = new Scanner(System.in);

    // add elements in the linked list
    llist.add(5);
    llist.add(4);
    llist.add(3);
    llist.add(2);
    System.out.println("LinkedList: " + languages);
    exchange(3,2);
    System.out.println("LinkedList: " + languages);
  }
  
  public static void exchange(int i, int j) {
    llist.set(i, llist.set(j, llist.get(i)));
}
  
}

Whenever I build this one there is no error that pops up, but when I run it, it gives me the java.lang.NullPointerException.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
mirkovski
  • 75
  • 2
  • 14

1 Answers1

0

Your line:

LinkedList<Integer> languages = new llist<>();

Has an error - replace it with

llist = new LinkedList<Integer>();

So it becomes

import java.util.LinkedList;
import java.util.Scanner;

public class Main {
    private static LinkedList<Integer> llist;
    public static void main(String[] args) {
        llist = new LinkedList<Integer>();
        Scanner s = new Scanner(System.in);

        // add elements in the linked list
        llist.add(5);
        llist.add(4);
        llist.add(3);
        llist.add(2);
        System.out.println("LinkedList: " + llist);
        exchange(3,2);
        System.out.println("LinkedList: " + llist);
    }

    public static void exchange(int i, int j) {
        llist.set(i, llist.set(j, llist.get(i)));
    }
}

Also

System.out.println("LinkedList: " + languages);

should be:

System.out.println("LinkedList: " + llist);

as you do not really use languages, but llist;

dmitryro
  • 3,463
  • 2
  • 20
  • 28