8

How to Print the Index or Obtain the Element of an Item in an Array List

 2 years ago
source link: https://www.codesd.com/item/how-to-print-the-index-or-obtain-the-element-of-an-item-in-an-array-list.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to Print the Index or Obtain the Element of an Item in an Array List

advertisements

So I'm making a program that makes random phone numbers. I've made an ArrayList of these phone numbers and I want to be able to search through my ArrayList and find the number (if it exists) and print both the index of it and the data contained.

Here is what I've gotten so far:

  public static ArrayList<String>phoneList = new ArrayList<String>();

  public static void main(String[] args)
  {
    Scanner s = new Scanner();

    for(int i = 0; i < 10; i++){
      phoneList.add(getPhoneNumber()); //getPhoneNumber returns a random phoneNumber
    }

    System.out.print("Enter Phone Number: ");
    String enteredNumber = s.nextLine();

    if(phoneList.containts(enteredNumber)){
      //tell me the index of that phone number in the list and
      //print out the phone number
    }

  }

I want to know how to do what's in the if statement.

Thanks!


if(phoneList.contains(enteredNumber)
{
     int index= phoneList.indexOf(enteredNumber);
     String number = phoneList.get(index);
}

This will give the index of that Number in the list as well as Number.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK