我有以下代码:
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]分配给姓氏。
答案 0 :(得分:1)
s[0]= strScan.next().split("/");
s[1]= strScan.next().split("/");
它会产生编译错误,split(" /")方法返回一个String数组。 如果我们假设你做了
s[0]= strScan.next().split("/")[0];
s[1]= strScan.next().split("/")[1];
然后你会在s [0]中获得第一个人的fisrtname,在s [1]中获得第二个人的姓氏。
你必须打电话
String[] datas=strScan.next().split("/");
s[0]=data[0];
s[1]=data[1];
或只是
s=strScan.next().split("/");
答案 1 :(得分:0)
使用String类的split方法,这将完全符合您的需要。
这就像一个魅力:
String names= "Jan/Albert/Bob";
String[] ns = names.split("/");
for ( String name : ns ){
System.out.println(name);
}
你的分裂代码怎么样? http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-
答案 2 :(得分:0)
String[] arr= theNames.split("/")
s[0]= aar[0]
s[1]= arr[1];
答案 3 :(得分:0)
Split
返回数组,因此使用index [0],[1]
while(strScan.hasNext()){
s[0]= strScan.next().split("//")[0];
s[1]= strScan.next().split("//")[1];
testArray[i]=new Name(s[0],s[1]);
i++;
}
但是你不需要将它放在另一个数组中,split本身会返回数组。