我对此问题感到困惑,我正在尝试输出名字和姓氏的缩写。我正在测试具有“ Mc” /“ Mac” /“ O'Connell”和“ O Connell”的姓氏,但是空格产生的错误类型-

全栈跟踪为:

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)


这是引发异常的代码:

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);
    }

}

最佳答案

这是因为您使用的是Scanner.next(),它将您的姓氏分为2个标记:oconnell。方法InitialsOutputfirstName = colmlastName = o调用。这就是lastName.codePointAt(1)给您错误的原因。

userInput.next();更改为userInput.nextLine();应该可以解决问题。

10-07 23:52