Taking input of different type in an ArrayList from user.

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

/**
 *
 * @author Sumit Tiwari
 */
class ArrayListUserInputDiffType {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        ArrayList ar = new ArrayList();
                
        System.out.println("Enter Data , enter 0 to stop : ");
        while (sc.hasNext()) // looping to take inputs
        {
                  
            if (sc.hasNextInt()) // check for int
            { 
              int n = sc.nextInt(); // taking int value from scanner
              if(n==0) // breaking the input loop
                  break;
              
                System.out.println("Integer added to ArrayList");
                ar.add(n); // adding Integer (autoboxed) to ArrayList

            }
            else if (sc.hasNextFloat())  // check for float
            {
                System.out.println("Float added to ArrayList");
                ar.add(sc.nextFloat()); // adding Float
            }
            else if (sc.hasNextBoolean()) // check for boolean
            {
                System.out.println("Boolean added to ArrayList");
                ar.add(sc.nextBoolean());
            }
            else // String input
            {
                System.out.println("String added to ArrayList");
                ar.add(sc.next());
            }
            
         System.out.println("Enter Data , enter 0 to stop : ");
        }
        
        System.out.println(" ArrayList : "+ar);
    }
}
OUTPUT:
Enter Data , enter 0 to stop : 
10
Integer added to ArrayList
Enter Data , enter 0 to stop : 
Hello
String added to ArrayList
Enter Data , enter 0 to stop : 
2.5
Float added to ArrayList
Enter Data , enter 0 to stop : 
true
Boolean added to ArrayList
Enter Data , enter 0 to stop : 
0
ArrayList : [10, Hello, 2.5, true]

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.