Java-以编程方式提取子字符串

时间:2019-06-27 17:39:30

标签: java

我正在尝试创建一个接受用户全名并返回名字和姓氏和首字母的代码。由于用户名称的长度各不相同,因此我不想使用硬编码,因此我以编程方式提取名称和缩写。 但是,当我运行它并输入名称时,出现以下错误消息:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1

我仔细查看了我的代码,看不到我在索引范围上误算的确切位置。我试图在这里找到类似的问题,但是尽管我确实看到了类似的问题,但它们与C ++或Perl(而非Java)有关。

package nameSubstring;

import java.util.Scanner;

public class NameSubstring {

    public static void main(String[] args) {

        /*
         * This is a program that accepts a user’s full name as a string (e.g. Margaret Thatcher) and displays to the user his/her first name, last name and initials in the following format:
           Your first name is Margaret and your last name is Thatcher and your initials are MT.
             */

        System.out.println("This program will take your full name and display your first name, last name, and initials.");
        Scanner scanner = new Scanner(System.in); 
        String firstName, lastName, firstNameInitial, lastNameInitial; 
        System.out.println("Please enter your full name, e.g. Jane Smith:");
        String fullName = scanner.next();
        int nameSpace = fullName.indexOf(' '); 
        firstName = fullName.substring(0, nameSpace); 
        lastName = fullName.substring(nameSpace)+1; 
        firstNameInitial = firstName.substring(0, 1);
        lastNameInitial = lastName.substring(0, 1);
        System.out.println("Your first name is " + firstName + ", " + "your last name is " + lastName + ", " + "and your initials are " + firstNameInitial + lastNameInitial + ".");

    }

}

1 个答案:

答案 0 :(得分:2)

使用next()代替nextLine()

String fullName = scanner.nextLine();

并使用+1更正错误,该错误必须在括号内:

lastName = fullName.substring(nameSpace+1);