So i have to make this contact book thing and i have just about got my head around the array list. Everything compiles, but when i enter everything in i get this error message:
java.lang.StringIndexOutOfBoundsException:
String index out of range:4 (in java.lang.String)
import java.util.ArrayList; /** * Write a description of class ContactList here. * * @author Tom Harvey * @version 1 */ public class ContactList { private ArrayList<Contact> contactList; public ContactList() { contactList = new ArrayList<Contact>(); } public void addPersonalContact(String fName, String sName, String street, String town, String partOnePC, String partTwoPC,int phoneNumber) { contactList.add(new Contact(fName, sName, street, town, partOnePC, partTwoPC)); } }
/** * Write a description of class Contact here. * * @author Tom Harvey * @version 1 */ public class Contact { protected String fName; protected String sName; protected String street; protected String town; protected String partOnePC; protected String partTwoPC; protected String postcode; public Contact(String fName, String sName, String street, String town, String partOnePC, String partTwoPC) { this.fName = fName; this.sName = sName; this.street = street; this.town = town; this.partOnePC = partOnePC; [U]if(partOnePC != null && (partOnePC.charAt(2) > 0 || partOnePC.charAt(3) > 0) && partOnePC.charAt(4) > 0)[/U] { System.out.println("Please insert a string with 3-4 characters"); } this.partOnePC = partOnePC; if(partTwoPC != null && (partTwoPC.charAt(2) > 0 || partTwoPC.charAt(3) > 0) && partTwoPC.charAt(4) > 0) { System.out.println("Please insert a string with 3-4 characters"); } this.postcode = partOnePC + " " + partTwoPC; } }
These are the two bits of code in the classes that are affected. I have underlined the code in which it has highlighted aswell


LinkBack URL
About LinkBacks
Reply With Quote
Probably should delete things like that when you paste to a public forum.
Have you ever think about the "length" of this partOnePC or partTwoPC? You can't simply assume that the position 4 of your String is existent, can you? No? Then you know how to make sure of this case? No? How about a question partXYZPC.length() >= 4 before you start to quest the charAt(4)?