我有以下代碼:如何拆分字符串並將拆分值分配給數組?
public static void main(String[] args) {
String Delimiter = "#";
Scanner scan = new Scanner(System.in);
System.out.println("Type in the number of names that you would like to store.");
int n = scan.nextInt();
System.out.println("Input the " +n+" names in the following format: "
+ "name/lastname#");
String theNames = scan.next();
Scanner strScan = new Scanner(theNames);
strScan.useDelimiter(Delimiter);
String [] s = new String[n];
Name [] testArray = new Name[n];
int i=0;
while(strScan.hasNext()){
s[0]= strScan.next().split("/");
s[1]= strScan.next().split("/");
testArray[i]=new Name(s[0],s[1]);
i++;
}
的問題是,我不能分割的姓名和由「/」分隔的姓氏。我想將s [0]分配給名字,將s [1]分配給姓。
你有一個邏輯上的錯誤在你的代碼。您要求「n」作爲名/姓對的數量,但用它來初始化用於存儲名和姓的數組。如果在名稱數量問題上輸入1,則代碼將失敗並顯示'ArrayIndexOutOfBoundsException' – blackbuild