该程序的目的是获取用户输入的全名,然后将其分解为他的名字和姓氏(除了做一些额外的事情)。
它应该在空格之间将String拆分成两半,但我只能引用split数组的第一个值,否则我得到:
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));
}
}
答案 0 :(得分:0)
你的问题是
fullName = input.next();
只读一个单词。你希望它是
fullName = input.nextLine();
将读取整行。