Home > database >  Add elements with user Input in a null ArrayList in Java
Add elements with user Input in a null ArrayList in Java

Time:03-18

I explain, I am trying to make the user enter five elements in a list with a fixed size of five elements; for this I have initialized these elements in null. My problem is that I don't know exactly how to do it for this particular case. I've tried this, but it's clearly not the right solution.

I made this code into two different empty constructor methods, to be used in a main class with the familiar main method. But this class is the one I have the most trouble with.

Btw! I want the user to add the elements, not me.

package HashArray;
import java.util.ArrayList;
import java.util.Scanner;
public class arrayListNull {
    public static void arrayList() {
         ArrayList<Integer> list = new ArrayList<Integer>();
         list.add(null);
         list.add(null);
         list.add(null);
         list.add(null);
         list.add(null);  
    }
    public static void inputUser() {
        Scanner scanner = new Scanner(System.in);
        for(int i=0 ; i < 5 ; i  ){
            arrayList.list.add(scanner.nextInt());
        }
        System.out.println(arrayList.list);
        scanner.close();
    }
}```

CodePudding user response:

You defined a public method named arrayList that returns nothing (void). That method (a) instantiates an ArrayList object, (b) populates the list with null references, which is redundant as nulls are the default, and (c) discards that ArrayList object by the end of the method. Poof, gone.

So your other method inputUser refers to a variable named arrayList which never existed.

Your code has many problems. You are not following Java naming conventions: classes start with uppercase, methods and variables lowercase. You are relying too much on static, likely a sign that you are not learning object-oriented concepts. And you seem to be coding blindly, without thinking it through, and without working with other example code. I suggest you review your textbook and the Java Tutorials provided by Oracle free-of-cost.

By the way, use try-with-resources syntax to automatically close resources such as Scanner objects.

CodePudding user response:

It is very likely that it is an activity of the training that you are doing and you are stuck. You can try this:

public static void inputUser() {
    List<Integer> arrayList = new ArrayList<>();
    int allowInputs = 5;

    Scanner scanner = new Scanner(System.in);
    for (int i = 0; i < allowInputs; i  ) {
        arrayList.add(scanner.nextInt());
    }
    scanner.close();

    System.out.println("Your specified elements:");
    arrayList.forEach(System.out::println);
}

// RUN
public static void main(String[] args) {
    inputUser();
}

good coding! ¯_(ツ)_/¯

  • Related