Java 如何拆分字符串并将拆分值分配给数组?

Java 如何拆分字符串并将拆分值分配给数组?,java,Java,我有以下代码: 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.o

我有以下代码:

 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]分配给first name,将s[1]分配给lastname。

使用String类的split方法,这将完全满足您的需要

这就像一个符咒:

String names= "Jan/Albert/Bob";
    String[] ns = names.split("/");
    for ( String name : ns ){
    System.out.println(name);
    }
你的拆分代码怎么样?

Split
返回数组,因此使用索引[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本身返回数组。

在您的代码中有两个错误:编译错误和逻辑错误。当你打电话的时候

    s[0]= strScan.next().split("/");
    s[1]= strScan.next().split("/");
它将给出一个编译错误,split(“/”)方法返回一个字符串数组。 如果我们认为你会的话

    s[0]= strScan.next().split("/")[0];
    s[1]= strScan.next().split("/")[1];
然后在s[0]中输入第一个人的FirstName,在s[1]中输入第二个人的姓氏

你必须打电话

String[] datas=strScan.next().split("/");
s[0]=data[0];
s[1]=data[1];
或者只是

s=strScan.next().split("/");

代码中存在逻辑错误。您要求“n”作为firstname/lastname对的数目,但使用它初始化用于存储first和lastname的数组。如果您在姓名数问题中输入1,您的代码将失败,出现
ArrayIndexOutOfBoundsException
第三个代码块中有一个打字错误(
s[2]
而不是
s[1]
)。另请参见我对问题的评论,
s
初始化错误。然而,您的简短示例(第4代码部分)将是足够和正确的。
s=strScan.next().split("/");