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?


1 2 3 4 5 6 7 8 | 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 } |
1 2 3 4 5 6 7 8 | 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 } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | /** * 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) { } } |
1 2 3 4 5 6 7 8 9 10 11 12 | 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++; } |