I am stumped on this problem, I am trying to output the initials of first name and last name. I am testing for last names that have an "Mc"/ "Mac" / "O'Connell" and "O Connell" but the space is producing an error of type ---
full stack trace is:
run:
Please enter First name :colm
Please enter Last name o connell
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:646)
at Initials2.InitialsOutput(Initials2.java:22)
at Initials2.main(Initials2.java:51)
Java Result: 1
BUILD SUCCESSFUL (total time: 13 seconds)
here is the code that throws an exception:
import java.util.Scanner;
public class InitialsTest {
public static void InitialsOutput(String firstName, String lastName){
// character array to hold the initials ex hellen walsh - output HW
char charInitials[] = new char[5];
charInitials[0] = firstName.charAt(0);
// test for different name types to output initials
// testing for mcMahon (which works)
// testing for o'donnell (which works)
// testing for macDonagh (which works)
// testing for O Connell (which fails - throws exception)
// the first test is for a blank space (which fails) or an ' (which works)
if (lastName.codePointAt(1) == '\u0020' | lastName.codePointAt(1) == 39){
//if (lastName.codePointAt(1) == 32 | lastName.codePointAt(1) == 39){
//if (lastName.codePointAt(1) == 0020 | lastName.codePointAt(1) == 39){
//if (lastName.charAt(1) == ' ' | lastName.codePointAt(1) == 39){
charInitials[1] = lastName.charAt(0);
charInitials[2] = lastName.charAt(2);
} else if ((lastName.charAt(0) == 'm' | lastName.charAt(0) == 'M')
& (lastName.charAt(1) == 'c' | lastName.charAt(1)== 'C')){
charInitials[1] = lastName.charAt(0);
charInitials[2] = lastName.charAt(2);
} else if ((lastName.charAt(0) == 'm' | lastName.charAt(0) == 'M')
& (lastName.charAt(1) == 'a' | lastName.charAt(1)== 'A')
& (lastName.charAt(2) == 'c' | lastName.charAt(2)== 'C')){
charInitials[1] = lastName.charAt(0);
charInitials[2] = lastName.charAt(3);
}
else {
charInitials[1] = lastName.charAt(0);
}
String initials;
initials = new String (charInitials);
System.out.println("Initials are : " + initials.toUpperCase());
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Please enter First name :");
String first = userInput.next();
System.out.print("Please enter Last name ");
String last = userInput.next();
InitialsOutput(first, last);
}
}
It's because you're using Scanner.next()
which breaks your last name into 2 tokens: o
and connell
. The method InitialsOutput
is called with firstName = colm
and lastName = o
. That's why lastName.codePointAt(1)
gives you the error.
Changing userInput.next();
to userInput.nextLine();
should do the trick.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.