我尝试了两个版本,但都重复打印出程序的其他部分。
版本1(带换行符)
try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
while(true) {
String input = br.readLine();
if(input != null) {
SomeRequest req = new SomeRequest();
req.text = input;
client.sendTCP(req);
} else {
System.out.println("non stop..."); <-- this continously prints
}
}
}
版本2(没有换行)
try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
while(true) {
String input = br.readLine();
if(input != null) {
SomeRequest req = new SomeRequest();
req.text = input;
client.sendTCP(req);
} else {
System.out.print("non stop..."); <-- this continously prints as well?
}
}
}
版本3(抛出异常)
try(Scanner sc = new Scanner(System.in)) {
String input = "";
System.out.println("Enter to send");
while(true) {
if(!sc.hasNextLine()) {
input = sc.nextLine();
SomeRequest req = new SomeRequest();
req.text = input;
client.sendTCP(req);
} else {
System.out.println("not sending");
}
}
}
我试图让用户在控制台上打印一些内容,然后将其发送到服务器,如您所见。但是现在这个程序只是打印不停......
答案 0 :(得分:1)
两个版本均无效。你没有在流结束时退出循环。它应该是:
try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
String input;
while ((input = br.readLine()) != null) {
SomeRequest req = new SomeRequest();
req.text = input;
client.sendTCP(req);
}
}
System.out.print("End of input");
}