尝试用空白 space 拆分字符串

Trying to split up a string with blank space

我正在编写一段代码,试图通过使用用户输入的值之间的空格将用户的输入分成 3 个不同的数组。但是,每次我 运行 我得到的代码都是错误的:

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
            at Substring.main(Substring.java:18)
    Java Result: 1

我曾尝试在输入文本时使用不同的分隔符,但效果很好,例如通常使用 / split 完全相同的输入,并且到目前为止做了我想要它做的事情。 任何帮助,将不胜感激! 如果需要,这是我的代码

import java.util.Scanner;

    public class Substring{
    public static void main(String[]args){
    Scanner user_input = new Scanner(System.in);

    String fullname = ""; //declaring a variable so the user can enter their full name
    String[] NameSplit = new String[2];
    String FirstName;
    String MiddleName;
    String LastName;

    System.out.println("Enter your full name (First Middle Last): ");
    fullname = user_input.next(); //saving the user's name in the string fullname

    NameSplit = fullname.split(" ");//We are splitting up the value of fullname every time there is a space between words
    FirstName = NameSplit[0]; //Putting the values that are in the array into seperate string values, so they are easier to handle
    MiddleName = NameSplit[1];
    LastName = NameSplit[2];

    System.out.println(fullname); //outputting the user's orginal input
    System.out.println(LastName+ ", "+ FirstName +" "+ MiddleName);//outputting the last name first, then the first name, then the middle name
    new StringBuilder(FirstName).reverse().toString();
    System.out.println(FirstName);


}

}

Split 是一个正则表达式,您可以查找一个或多个 spaces (" +") 而不是只查找一个 space (" ")。

String[] array = s.split(" +");

或者您可以使用 Strint Tokenizer

 String message = "MY name is ";
 String delim = " \n\r\t,.;"; //insert here all delimitators
 StringTokenizer st = new StringTokenizer(message,delim);
 while (st.hasMoreTokens()) {
     System.out.println(st.nextToken());
 }

您在以下地方犯了错误:

fullname = user_input.next();

它应该是 nextLine() 而不是 next() 因为你想从扫描器中读取完整的行。

String[] NameSplit = new String[2];

不需要此步骤,因为您稍后会执行 NameSplit = user_input.split(...),但它应该是 new String[3] 而不是 new String[2],因为您要存储三个条目,即名字、中间名和姓氏。

这是正确的程序:

class Substring {
    public static void main (String[] args) throws java.lang.Exception {
        Scanner user_input = new Scanner(System.in);
        String[] NameSplit = new String[3];
        String FirstName;
        String MiddleName;
        String LastName;

        System.out.println("Enter your full name (First Middle Last): ");
        String fullname = user_input.nextLine();

        NameSplit = fullname.split(" ");
        FirstName = NameSplit[0];
        MiddleName = NameSplit[1];
        LastName = NameSplit[2];

        System.out.println(fullname);
        System.out.println(LastName+ ", "+ FirstName +" "+ MiddleName);
        new StringBuilder(FirstName).reverse().toString();
        System.out.println(FirstName);
    }
}

输出:

Enter your full name (First Middle Last): John Mayer Smith

Smith, John Mayer

John

java.util.Scanner 使用分隔符模式将其输入分成标记,默认情况下匹配空格。 因此,即使您输入了 'Elvis John Presley',也只有 'Elvis' 存储在 fullName 变量中。 您可以使用 BufferedReader 读取整行:

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    try {
        fullname = reader.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }

或者您可以使用以下方法更改扫描仪的默认行为: user_input.useDelimiter("\n"); 方法。

异常清楚地表明您超出了数组的长度。 LastName = NameSplit[2] 中的索引 2 超出数组范围。要消除错误,您必须:

1-String[] NameSplit = new String[2]改成String[] NameSplit = new String[3]因为数组长度应该是3。

在此处阅读更多内容:[How do I declare and initialize an array in Java?]

至此,错误消失了,但解决方案还不正确,因为 NameSplit[1]NameSplit[2]null,因为 user_input.next(); 只读取第一个单词 ( *基本上直到检测到空格(或 '\n' 如果只有一个单词)。所以:

2-user_input.next(); 更改为 user_input.nextLine(); 因为 nextLine() 读取整行(*基本上直到出现 '\n'检测到)

在此处阅读更多内容:[http://www.cs.utexas.edu/users/ndale/Scanner.html]