I know the contains method tests to see if a string contains at least one of the letters you entered, but how do I set it to test if there's one at the most?
String myString; ... int firstIndex = myString.indexOf( something ); int lastIndex = myString.lastIndexOf( something ); if (firstIndex != -1 && firstIndex == lastIndex) { // Only one occurrence of something in myString. Where something is another String or just a char }
String myString; ... int firstIndex = myString.indexOf( something ); int lastIndex = myString.lastIndexOf( something ); if (firstIndex != -1 && firstIndex == lastIndex) { // Only one occurrence of something in myString. Where something is another String or just a char }
/** * Constructor for objects of class FriendList */ public FriendList() { friend = new ArrayList<Person>(); } public void add(Person p) { friend.add(p); } public Person get(int index) { if (index >= 0 && index < friend.size()) { return friend.get(index); } else { return null; } } public boolean purge(int index) { if (index >= 0 && index < friend.size()) { friend.remove(index); return true; } else { return false; } } public void putLast(int index) { if (index >= 0 && index < friend.size()) { Person end = friend.remove(index); friend.add(end); } } public void list() { int index = 0; while(index < friend.size()) { Person x = friend.get(index); System.out.println("Friend's Name: " + x.getName()); System.out.println("Friend's Number: D00" + x.getMemberNumber()); System.out.println(); index++; } } public void listContainingAtLeastOne(String str) { int index = 0; while(index <friend.size()) { Person x = friend.get(index); if (x.getName().contains(str)) { System.out.println(x.getName()); } index++; } } public void listContainingAtMostOne(String str) { } }
int index = 0; while(index < friend.size()) { Person x = friend.get(index); int firstIndex = x.getName().indexOf(str); int lastIndex = x.getName().lastIndexOf(str); if (firstIndex != -1 && firstIndex == lastIndex) { friend.remove(x.getName()); } index++; }