【问题标题】:Trying to split up a string with blank space试图用空格分割一个字符串
【发布时间】:2016-10-18 18:05:32
【问题描述】:

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

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

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

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


}

}

【问题讨论】:

  • 你为什么要做 fullname.split("\\ ") 而不是 fullname.split(" ")?我很确定我以前做过这个,而且效果很好。
  • 是的,但你没有告诉我们你输入了什么,所以..
  • 那不应该在那里,我的错
  • 我输入了所要求的内容,例如“猫王约翰普雷斯利”
  • 尝试打印出全名。我在这里没有发现问题。

标签: java arrays split delimiter


【解决方案1】:

Split 是一个正则表达式,您可以查找一个或多个空格(“+”)而不是一个空格(“”)。

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

【讨论】:

    【解决方案2】:

    你在以下地方犯了错误:

    全名 = 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);
        }
    }
    

    输出:

    输入您的全名(First Middle Last):John Mayer Smith

    史密斯,约翰·迈耶

    约翰

    【讨论】:

    • 它是 String[2],因为第一个值为 0,第二个为 1,第三个为 2 :) 不过还是谢谢你的帮助!
    • @L.Jones28 请记住,索引从0 开始,当您保留空间时,索引的概念不再成立。所以应该是3 而不是2
    【解决方案3】:

    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"); 方法。

    【讨论】:

      【解决方案4】:

      异常清楚地表明您超出了数组的长度。 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]

      【讨论】:

        猜你喜欢
        • 2012-04-22
        • 2012-09-22
        • 2020-05-16
        • 1970-01-01
        • 1970-01-01
        • 2014-12-13
        • 2013-08-02
        • 2023-04-02
        • 2013-10-11
        相关资源
        最近更新 更多