Reputation: 91
I am trying to do a telephone directory using arrays (I have to use arrays). I am trying to write the method for adding new entries. I decided to add a new entry with a line that will be split using the split
method into three parts (surname, initials, number) with tabs. When I tried to do the testing for the method I got thrown an IndexOutOfBoundsException
.
This is the addEntry
method
@Override
public void addEntry(String line) {
String[] entryLine = line.split("\\t");
String surname = entryLine[0];
String initial = entryLine[1];
String number = entryLine[2];
Entry entry = new Entry(surname, initial, number);
count++;
if (surname == null || initial == null || number == null) {
throw new IllegalArgumentException("Please fill all the required fields, [surname,initials,number]");
}
if (count == entries.length) {
Entry[] tempEntries = new Entry[2 * count];
System.arraycopy(entries, 0, tempEntries, 0, count);
entries = tempEntries;
} else {
int size = entries.length;
for (int i = 0; i < size - 1; i++) {
for (int j = i + 1; j < entries.length; j++) {
String one = entry.getSurname();
if (one.toLowerCase().compareTo(surname.toLowerCase()) > 0) {
Entry tempE = entries[i];
entries[i] = entries[j];
entries[j] = tempE;
}
}
}
}
}
This is the entry I tried to add:
arrayDirectory.addEntry("Smith SK 005598");
Upvotes: 0
Views: 84
Reputation: 1900
Instead of having the logic:
if (surname == null || initial == null || number == null)
{
throw new IllegalArgumentException("Please fill all the required fields, [surname,initials,number]");
}
You should check the split line has length 3:
String[] entryLine = line.split("\\s+");
if (entryLine.length() != 3)
{
throw new IllegalArgumentException("...");
}
Because those variables wont be null, the array access will cause IOOB error.
Also you should be putting
Entry entry = new Entry(surname, initial, number);
count++;
after the size check (better to put all precondition checks at the start of the method).
Upvotes: 1
Reputation: 21104
If the String
you're entering is really
Smith SK 005598
Then your splitting regex
\\t
(tab) cannot work, as the pieces are not separated by tabs.
Instead, you need to use
line.split("\\s+");
As \s+
will match any number of spaces.
The output will correctly result in
[Smith, SK, 005598]
To have each piece separated by a tab, you'd use
Smith\tSK\t005598
Only then your original regex will work.
Upvotes: 2