Reputation: 23
The program isn't printing out the thanks (name). Instead, the line is being skipped completely, looping back to the main menu. Can someone please explain why? It should be creating a new string based on the indexes indicated and storing the result in 'firstName' then printing it out as "Thanks (name)!"
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String[] custInfo = new String[20];
String MANAGERID = "ABC 132";
String userInput;
String cust = "Customer";
String pts = "Print to screen";
String exit = "Exit";
int counter = 0;
int full = 21;
boolean cont = true;
while(cont) {
System.out.println("Enter the word \"Customer\" if you are a customer or your ID if you are a manager.");
userInput = in.nextLine();
if (userInput.equalsIgnoreCase(exit)) {
System.out.println("Bye!");
System.exit(0);
}
try {
if (userInput.equalsIgnoreCase(cust)) {
System.out.println("Hello, please enter your name and DoB in name MM/DD/YYYY format.");
custInfo[counter] = in.nextLine();
String firstName=custInfo[counter].substring(0,(' '));
System.out.println("Thanks "+firstName+"!");
counter++;
}
if (counter==full) {
System.out.println("Sorry, no more customers.");
}
} catch(IndexOutOfBoundsException e) {
}
}
}
Upvotes: 1
Views: 103
Reputation: 592
Your code is generating an IndexOutOfBoundsException
on the line below and jumping to the Exception handler code.
String firstName=custInfo[counter].substring(0,(' '));
String.substring
is overloaded and has two definitions:
substring(int startIndex)
substring(int startIndex, int endIndex)
In Java, a char
data type is simply a 16-bit number behind the scenes. It is converting ' '
(space) into 32 and will error on any String that is shorter than that (presuming counter is pointing to a valid index)
Upvotes: 4
Reputation: 3759
Use this instead custInfo[counter].indexOf(" ")
to get the index of the space between name and DoB:
String firstName = custInfo[counter].substring(0, custInfo[counter].indexOf(" "));
Upvotes: 1