1

I am trying to take User Input in one line and store in Array List. For Example I want to take User Input to sort the maximum and Minimum values of the given input. I am looking for some code suggestions on how an Array List can take input in one Line.

Below is the Code that I am using. Please review and provide better inputs and suggestions

    public static void main(String[] args) {
  //1.take input from user
  Scanner input = new Scanner(System.in);
  //2.store them in an arraylist
  ArrayList<Integer> al = new ArrayList<Integer>();
   
    
    while(true){
    System.out.println("Enter the Array elements :");
    int in = input.nextInt();
    al.add(in);
        System.out.println("Are array elements entered ? Type \"yes\" if finished or else enter no");
        String answer = input.next();
        if(answer.equalsIgnoreCase("yes")){
            break;
        }
    }
    System.out.println("Entered array elements are:");
    //we can simply print here or to retrieve them we have to iterate elemets
    
    for(Integer a:al){
        System.out.println(a);
    }
    System.out.println("Array elemets :"+al);
    Collections.sort(al);
    System.out.println("Sorted array: "+ al);
  
}

Here if I give User Input seperated by comma(,) it throws InputMismatchException . I cannot give here User Input as 12,2,1,5,10 .The above code doesn't read all the values in one line and store . I have to give one input at a time and then have to give yes if Array List input is completed else no to continue to give user input. I am beginner in Java. Looking for some better code and suggestions. Any Kind help is appreciated.

1
  • 1
    Read the entire line, split the string by comma (or whatever delimiter you need), iterate the resulting array, parse each element to int and add to the list. You can also research how to do it with Stream API. Commented May 23, 2023 at 17:37

1 Answer 1

1

To allow for the user to input a list of integers, comma separated, you can use the following.

String[] values = input.nextLine().split(", *");
for (String value : values)
    al.add(Integer.parseInt(value));

This will capture the entire line, then use the String.split method to create an array of strings, using the comma and optional space as the delimiter.

Then, we can iterate through each String value and use the Integer.parseInt method to parse the value to an int.

Input

12,2,1,5,10

Output

Entered array elements are:
12
2
1
5
10
Array elemets :[12, 2, 1, 5, 10]
Sorted array: [1, 2, 5, 10, 12]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.