How to take User input to an ArrayList which can accept any Objects, and help me out in accepting only STRING's too #java

Viewed 26

Here my code just accepts Integers type. if i enter any other type other than INT it exits out of loop and i need a code which accepts string and it should exit the loop if we enter a Int type.

import java.util.*;
class AL
{
    public void alMethod() 
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter your input: ");
        ArrayList<Integer>alobj = new ArrayList<>();    '//ArrayList of which accepts Integer'
            while( sc.hasNextInt())           '//used for adding the Int objects in ArrayList'
            {                                              
                alobj.add(sc.nextInt() );
            } 
        System.out.println("\n"+"AL ---> "+alobj + "\n");
        System.out.println("---- Iterating the ARRAYList ----");
        for(int var : alobj) 
        {                                                '//loop to iterate on arrayList'
            System.out.println(var);
        }
    }
}
public class Iterating_ArrayList 
{
   public static void main(String[] args) 
    {
        AL obj = new AL();                               '//ObjectCreation for AL class'
        obj.alMethod();
    }
}
1 Answers

To read a mixed list of strings and numbers:

Scanner sc = new Scanner(System.in);
List<Object> alobj = new ArrayList<>();
System.out.println("Enter your input: ");
// What condition ends the loop??
while (sc.hasNext()) {
    // Read next as a string
    String input = sc.next();
    // First, try to convert to integer and add
    try {
        int number = Integer.parseInt(input);
        alobj.add(number);
    }
    catch (Exception e) {
        // Add as integer failed so add as string
        alobj.add(input);
    }
}
alobj.forEach(System.out::println);
Related