Search an Element in Arraylist in java | Programming Hub

Array List In java

Code:

package labno1;
import java.util.ArrayList;
import java.util.Scanner;
public class ArraylistSearch {
     public static void main(String[] args) {
        Scanner n = new Scanner(System.in);
         ArrayList<String> obj = new ArrayList<String>();
         System.out.println("Enter length of Array list");
         int elem;
         elem = n.nextInt();
          System.out.println("Enter Array values");
         for (int i = 0; i < elem; i++) {
             obj.add(n.next());
          } 

    String k;
         System.out.println("Enetr No to Search");
         k = n.next();
         boolean e = obj.contains(k);
         System.out.println("Number Found ="+e);
         int no = obj.indexOf(k);
         if(no==-1){
             System.out.println("No index not found");
         }
         else {
             System.out.println("Number is "+k+" Found at index "+no);
         }
        
    }}

Output:

run:
Enter length of Array list
4
Enter Array values
2
3
4
5
Enetr No to Search
5
Number Found=true
Number is 5 Found at index 3

 



Comments

Popular posts from this blog

GUI in Java | How to make userdefined login page in graphical user interface in java

Multiple Inheritence in Java /How to inherit a class from another in Java| Programmer Hub