Search code examples
javaarraysarraylistuser-inputuser-defined-functions

Pass User Input to the ArrayList and display the output


I Need Help In Programming Where The ArrayList Should Take The User Input Of Integer Type And Store them . The Size Cannot Be Specified by user Priorly and It Should Take As Many Elements As the user can Add. It Should Ask If The Inputs For ArrayList Is Done. If Given Yes It Should End And Display The ArrayList Data Entered By The User. If Other Than Yes It Should Still Continue To Take The Input To Add Elements In Arraylist. Please Help


Solution

  • You should create an infinite loop with while, and create the condition for break;. Use Scanner to read input by the method nextInt() for ArrayList elements and nextInt() for string "yes".

    import java.util.ArrayList;
    import java.util.Scanner;
    
    public class UserInputArrayList {
        public static void main(String[] args) {
            ArrayList<Integer> numbers = new ArrayList<>();
            Scanner scanner = new Scanner(System.in);
    
            while (true) {
                System.out.println("Enter an integer to add to the ArrayList:");
                int input = scanner.nextInt();
                numbers.add(input);
    
                System.out.println("Is the input for ArrayList done? (Type 'yes' to finish, anything else to continue)");
                String done = scanner.next();
                if (done.equalsIgnoreCase("yes")) {
                    break;
                }
            }
    
            System.out.println("The ArrayList data entered by the user:");
            for (int number : numbers) {
                System.out.println(number);
            }
    
            scanner.close();
        }
    }