【问题标题】:Splitting String after whitespace and then referencing it在空格后拆分字符串然后引用它
【发布时间】:2015-05-11 08:23:38
【问题描述】:

该程序的目的是获取用户输入的他的全名,然后将其分解为他的名字和姓氏(除了做一些额外的事情)。

它应该在空格之间将字符串分成两半,但我只能引用拆分数组的第一个值,否则我会得到:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at FirstNameLastName.main(FirstNameLastName.java:41)

这是当前的代码,任何帮助将不胜感激:

import java.util.Scanner;

public class FirstNameLastName {

    public static void main(String[] args) {    
        String fullName; //the users full name as he enters it          
        String fname; //the users first name
        int fnameCount; //number of characters in fname
        String lname; //the users last name;
        int lnameCount; // counts amount of characters in lname
        String init; //initials of the user, combination of first and last name

        Scanner input = new Scanner(System.in);
        System.out.println("Please input your first and last name with a space inbetween them");
        fullName = input.next();

        String[] parts = fullName.split("\\s+"); // creates an array within which the two split String values are stored
        fname = parts [0];  
        lname = parts [1];      
        fnameCount = fname.length();
        lnameCount = lname.length();

        System.out.println(fname);
        System.out.println(lname);      
        System.out.printf("Your first name is %s , which has %d characters" , fname , fnameChar);
        System.out.println();
        System.out.printf("Your last name is %s , which has %d characters" , lname , lnameChar);
        System.out.println();
        System.out.printf("Your initials are %c%c", fname.charAt(0),lname.charAt(0));

    }
}

【问题讨论】:

  • 如果你检查parts.length,你会得到什么?
  • 它清楚地表明数组只有 1 个元素,你是如何将输入传递给这个程序的。例如"FirstName LastName" 或 FirstName LastName

标签: java arrays regex split indexoutofboundsexception


【解决方案1】:

你的问题是

fullName = input.next();

它只读取一个单词。你希望它是

fullName = input.nextLine();

它将读取整行。

【讨论】:

  • 哦。是的,解决了它。我假设下一个包括整行。我会记住这一点以供将来参考,谢谢。
猜你喜欢
  • 2017-06-18
  • 1970-01-01
  • 1970-01-01
  • 2019-01-13
  • 1970-01-01
  • 2015-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多