Reputation: 542
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!
Upvotes: 1
Views: 2728
Reputation: 294
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.
Upvotes: 2
Reputation: 4940
Simply iterate through that list.
for(int i=0; i<phoneList.size(); i++){
if(phoneList.get(i).equals(phoneNumber)){
System.out.println("Index: "+i);
System.out.println("PhoneNumber: "+phoneNumber);
break;
}
}
Upvotes: 1