ArrayList只有一个条目Java

时间:2014-06-29 08:56:54

标签: java arrays list

我有一个arraylist,我每次运行我的客户端时都会尝试添加一些新玩家,但我只添加了一个玩家。我确定我的arraylist和id是否公开以及你如何在我运行的每个帖子中使用它们

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class server {
    @SuppressWarnings("resource")
    public static void main(String[] args) throws IOException {
        ServerSocket socketS = null;

        try {
            socketS = new ServerSocket(4444);
        } catch (IOException e) {
            System.err.println("Could not listen on port: 4444.");
            System.exit(-1);
        }
        while (true)
            new ServerClass(socketS.accept()).start();
    }
}

class ServerClass extends Thread {
    public int id = 0;
    Socket s;
    game g;
    private boolean ft = true;
    DataInputStream in;
    DataOutputStream out;
    private int currid2;
    private int currid1;
    private String name1, name2;
    List<player> players = new ArrayList<player>();

    public ServerClass(Socket s) {
        super("NewPlayer");
        players.add(id, new player(id, s));
        System.out.println(players.size() + "  " + id);
        this.s = s;
        id++;
    }

    public void run() {
        try {
            in = new DataInputStream(s.getInputStream());
            out = new DataOutputStream(s.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if ((id % 2) != 0) {

            while ((id % 2) != 0) {
                try {
                    Thread.sleep(10);

                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
            while (true) {
                try {
                    String message = null;
                    while (message == null) {

                        message = in.readUTF();
                    }
                    if (ft != true) {
                        String x = Thread.currentThread().getName();
                        System.out.println(" " + message + " \n" + players.get(id).getID() + "  " + players.get(id).getS());
                        System.out.println("Thread name: " + x);
                        out.writeUTF("over");
                    } else {
                        out.writeUTF("Give me your name");
                        name2 = in.readUTF();
                        currid2 = g.getID2();
                        players.get(currid2).setName(name2);
                        ft = false;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            while (true) {
                try {

                    //g = new game(players.get(0), players.get(1));
                    String message = null;
                    while (message == null) {
                        message = in.readUTF();
                    }
                    if (ft != true) {
                        String x = Thread.currentThread().getName();
                        System.out.println(" " + message + " \n" + players.get(id).getID() + "  " + players.get(id).getS());
                        System.out.println("Thread name: " + x);
                        out.writeUTF("over");
                    } else {
                        out.writeUTF("Give me your name");
                        name2 = in.readUTF();
                        currid2 = g.getID2();
                        players.get(currid2).setName(name2);

                    }
                } catch (IOException e) {
                    in = null;
                    out = null;
                }

            }
        }

    }
}

2 个答案:

答案 0 :(得分:0)

你创建了一个包含&#34;玩家&#34;的ArrayList,所以你需要像这样添加一个玩家到你的列表中:           players.add(新玩家(id,s)); 但我没有看到任何球员级别。顺便说一下,类应始终以大写字母开头。 你的代码很漂亮......混合起来。

我希望我的回答是正确的。

答案 1 :(得分:0)

要将玩家添加到ArrayList,您需要调用List.add方法。您已经在ServerClass构造函数中执行了一次。你在这一行只添加了一名玩家players.add(id, new player(id, s));
你需要添加更多这样的线条。例如:

players.add(new player(++id, s));
players.add(new player(++id, s));
players.add(new player(++id, s));

这些行将在您的列表中添加额外的3个玩家。但是,您需要编写用于为玩家创建唯一ID的逻辑,并确定何时需要添加新玩家。

编辑:如果您需要在每次连接客户端时添加新玩家,并且根据我的代码理解,“ServerClass”是将处理客户端的类。那么你需要在ServerClasses之间共享ArrayList。目前,每个ServerClass对象都将创建一个新的ArrayList(我们不希望这样)。

将玩家列表添加到Game对象怎么样?我认为Game对象是在所有客户端之间共享的。

public interface PlayerProviderable
{
    Player createNewPlayer(Socket socket);
    Player getPlayer(int key); // maybe the key is an index...depending on implementation
}

public class Game implements PlayerProviderable
{
    // fields as usual...
    // constructor as usual

    // add a List for the player here...or a map.
    // Map<Integer, Player> players = new HashMap<Integer, Player>();
    List<Player> players = new ArrayList<Player>(); // if this is the list implementation. consider using a Map instead.

    public synchronized Player createNewPlayer(Socket socket)
    {
         // add the player to a list or to a dictionary.
         // this is the List implementation.
         int id = players.size();
         players.add(new Player(id, socket));

         //players.put(id, new Player(id, socket)); // to a map.
    }

    public synchronized Player getPlayer(int key)
    {
        // retrieve a player from a list or from a dictionary with the given key. the key is the id or the index. You decide.
       // it could be better to use a Map here instead of a list.
       // but this is the a simple list implementation; Will throw an exception or return null (implementation specific) if the key does not exists.

        return players.get(key); // as we did not provide a method to delete a player. Otherwise, you will need to iterate over all of the players and find the one with the id you wanted. 
        // or just use a Map instead of a list.

    }
}

然后在ServerClass中(无论名称是Server的客户端类):

public class ServerClass extends Thread
{
    // all the fields you need. minus the List<Player>.

    public ServerClass(Game game, Socket s)
    {
        super("NewPlayer");

        g = game;  // g is the name that you used. consider changing it to a better name.

        // continue initialization as normal.
        // you do not need the key

        game.createNewPlayer(s);
    }

    // at the run method.
    public void run()
    {
        //start as usual...

        else 
        {
            out.writeUTF("Give me your name");
            name2 = in.readUTF();
            currid2 = g.getID2();
            Player player = game.getPlayer(currid2);
            if(null != player)
            {
                player.setName(name2);
            }

            ft = false;
        }

        // continue as usual...
    }
}

主要是:

public class Server
{
    public static void main(String ... args) throws IOException // It is better to catch it here...otherwise your app will be terminated.
    {
        // as usual...

        Game game = new Game( ... ); // create your game here.

        while(true) // consider to use a flag or other logic for stopping.
            new ServerClass(game, socketS.accept()).Start();

        // as usual...
}