【发布时间】:2016-03-17 22:54:50
【问题描述】:
我一直在制作一个即时聊天程序,并希望让用户可以互相“耳语”或私信。我实现的方式是用户输入:
/w [用户名] [消息]
然后我将它发送到服务器,该服务器将它发送给所有用户。然后用户必须检查它是否发送给他们,这就是那个方法:
if (message.startsWith("/msg/")) {
message = message.trim();
message = message.substring(5);
String[] words = message.split("//s");
String UserName = null;
try {
String username = words[2];
UserName = username;
System.out.println(UserName);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error reading the whisper command!");
}
if (UserName == client.getName()) {
List<String> list = new ArrayList<String>(Arrays.asList(words));
list.removeAll(Arrays.asList(2));
words = list.toArray(words);
String text = words.toString();
text = "You've been whispered! " + message;
console(text);
}
每次我在测试时发送 /w 时,总是会给出 ArrayIndexOutOfBoundsException。我还在发送中修改了消息。继承人的方法:
else if (message.toLowerCase().startsWith("/w")) {
message = "/msg/" + client.getName() + message;
message = "/m/" + message + "/e/";
txtMessage.setText("");
}
我还为用户的实际代码添加了一大堆更多选项,我将其设为 /whisper、/m、/msg 和 /message,但这些只是具有不同输入的副本。为什么它给我一个 ArrayIndextOutOfBoundsException,当单词数组中的第三位应该是发件人试图将其发送到的用户名时。显然这可能不是发送私人消息的最佳方式,如果你们中的任何人有一个更简单的方式我可以在我的服务器上实现,请继续告诉我!只要知道我是一个年轻的新程序员,所以我可能会有很多问题。
【问题讨论】:
-
您的测试信息是什么?
-
您不会访问数组索引并捕获 ArrayIndexOutOfBounds。在访问之前检查数组或数组列表的长度。其他语言在这里有不同的概念;但在 Java 中,您首先检查以确保您想要访问的东西在您访问之前确实存在。拆分字符串总是会导致意想不到的结果;所以先检查!
-
您的意思是
\\s而不是//s?
标签: java