当我启动服务器并且客户端连接到它时,我收到此错误:
Waiting for clients ...
Client connected from: Driton PC
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
我不太明白为什么会发生这种情况,当我从互联网上跟随另一个人并且他的示例有效而我的示例无效时
public class ChatServer {
public static ArrayList<Socket> ConnectionArray = new ArrayList<Socket>();
public static ArrayList<String> CurrentUsers = new ArrayList<String>();
public static void main(String[] args) throws IOException{
try
{
final int PORT = 444;
ServerSocket SERVER = new ServerSocket(PORT);
System.out.println("Waiting for clients...");
while(true)
{
Socket SOCK = SERVER.accept();
ConnectionArray.add(SOCK);
System.out.println("Client connected from: "+ SOCK.getLocalAddress().getHostName());
AddUserName(SOCK);
Chat_Server_Return CHAT = new Chat_Server_Return(SOCK);
Thread x = new Thread(CHAT);
x.start();
}
}
catch(Exception x){System.out.println(x);}
}
public static void AddUserName(Socket X) throws IOException
{
Scanner INPUT = new Scanner(X.getInputStream());
String UserName = INPUT.nextLine();
CurrentUsers.add(UserName);
for(int i = 1; 1 <= ChatServer.ConnectionArray.size(); i++){
Socket TEMP_SOCK = (Socket) ChatServer.ConnectionArray.get(i-1);
PrintWriter OUT = new PrintWriter(TEMP_SOCK.getOutputStream());
OUT.println("#?!"+ CurrentUsers);
OUT.flush();
}
}
它运行 for
循环两次。
最佳答案
如果没有删除任何内容,则 for
循环的条件不正确。更改为:
i <= ChatServer.ConnectionArray.size()
但是处理 for 循环的传统方法是遵循从 0 开始的索引,并且而不是稍后减一:
for(int i = 0; i < ChatServer.ConnectionArray.size(); i++){
Socket TEMP_SOCK = (Socket) ChatServer.ConnectionArray.get(i);
关于java - 如何从 ArrayList 中摆脱 IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15840802/