【发布时间】: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