Java分割输入
我正在尝试读入命令和名称。例如“名称:”+“用户名”,我想将用户名添加到数组列表中。我正在尝试拆分输入,以便我有一个名称变量和一个用户名变量,如下所示:
public void run() {
String line;
try {
while(true) {
line = input.readLine();
String[] temp;
temp = line.split(":");
//checks different input from the client
//checks to see if the client wants to terminate their connection
//removes the client's name from the list
if("name:".equals(temp[0])) {
users.add(temp[1]);
output.println("OK");
}
else {
broadcast(name,line); // method in outer class - send messages to all
}
} // end of while
} catch(Exception e) {
System.out.println(e.getMessage());
}
} // end of run()
I am trying to read in a command and a name. For example "name:" + "username" and I want to add the username to an arraylist. I am trying to split the input, so that I have a name variable and a username variable as shown below:
public void run() {
String line;
try {
while(true) {
line = input.readLine();
String[] temp;
temp = line.split(":");
//checks different input from the client
//checks to see if the client wants to terminate their connection
//removes the client's name from the list
if("name:".equals(temp[0])) {
users.add(temp[1]);
output.println("OK");
}
else {
broadcast(name,line); // method in outer class - send messages to all
}
} // end of while
} catch(Exception e) {
System.out.println(e.getMessage());
}
} // end of run()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
split
吞掉了分隔符,因此您需要将 this: 更改为这样:
另外, this:
似乎有点奇怪,因为它引用了一个名为
name
的变量,但什么也没有在您发布的代码片段中声明该变量,或者(除了这一行)引用它。split
swallows the separator, so you need to change this:to this:
Also, this:
seems a bit odd, in that it refers to a variable named
name
, but nothing in your posted snippet declares that variable, or (aside from this line) refers to it.