输入:

R Henry Lily

R Victor

M

所需的输出:

The members are Henry, Lily, Victor

我的代码是:

  code = sc.next();
     while (sc.hasNext()) {
        if (code.equals("R")) {
            while(sc.hasNext()) {
                socialNetwork.registerUser(sc.next());
            }
        else if (code.equals("M"))
            System.out.print("The members are " + socialNetwork.toString());
        code = sc.next()
    }


社交网络是我在另一个程序中创建的修改后的数组类。但是这些部分没有按照我的意愿注册。它没有保存为[Henry, Lily, Victor],而是保存了[Henry, Lily, R, Victor]

最佳答案

您永远不会退出内部循环while(sc.hasNext()),即使您愿意,也永远不会取回第一个while(sc.hasNext())中的代码,因此只会读取第一个代码,而所有其他代码都将被注册。您可能没有尝试使用M选项,因为使用它也不起作用,只需注册M。让我相信您还没有尝试过的另一件事是,您使用socialNetwork.toString()输出最终数组,这将输出对象的内存地址。在这里,我修改了您的算法以适合您的需求:

Scanner sc = new Scanner(System.in);
String code;
String tmpLine;

while (sc.hasNext()) {
    code = sc.next();//retrieve the code
    if (code.equals("R")) {
        tmpLine = sc.nextLine().trim();//read the entire rest of the line
        for(String s : tmpLine.split(" "))// split words by space
            socialNetwork.registerUser(s);
    }
    else if (code.equals("M"))
    {
        System.out.print("The members are " + String.join(",", socialNetwork));//notice that I use String.join instead of toString
    }
}

09-10 15:28