I have been presented with this code which looks unnatural to me. I would normally use hasNextLine() rather than a Boolean variable done as shown in this code in the while loop, but now I’m confused. My question is, can I replace the logic where the variable done is shown with hasNextLine() when input is expected from the console, or can I only use hasNextLine() when input comes from a file? Which is a better practice way of implementing this code where input comes from console, by using the done variable or hasNextLine()? Thanks.
// TCPClient.java
import java.net.*;
import java.io.*;
import java.lang.*;
public class TCPClient{
public static void main(String args[]){
Socket clientSock=null;
try{
int port_num = Integer.valueOf(args[1]).intValue(); //get server's port no.
clientSock = new Socket(args[0],(int)port_num); // args[0] is the server host name
/* String sock=clientSock.toString();
System.out.println(sock); */
PrintWriter oStream =
new PrintWriter(clientSock.getOutputStream(),true);
BufferedReader iStream =
new BufferedReader(new InputStreamReader
(clientSock.getInputStream()));
BufferedReader keyInput =
new BufferedReader(new InputStreamReader(System.in));
boolean done = false;
String answer = iStream.readLine();
if(answer != null)
System.out.println(answer);
while(!done){
String line = keyInput.readLine();
if(line.trim().equals("BYE"))
done = true;
oStream.println(line);
answer = iStream.readLine();
if(answer != null)
System.out.println(answer);
}
clientSock.close();
}catch(Exception e){
System.out.println(e);
}
}
}
There is a bug in @Voo’s solution because the
nextLine()onkeyInputcould also returnnull. Here’s a corrected version:You can wrap any
InputStreamor anyReadable(of whichReaderis a subtype) in aScanner, allowing you to usehasNextLine()on all of them. The only caveat is thathasNextLine()can potentially block indefinitely waiting for input if the underlying stream comes from a console, pipe, socket or similar.Either will do, as will the third option as illustrated above. It is really a matter of taste … and what you think looks simplest. (Personally, I’d not use
Scannerjust so that I can callhasNextLine()… but that’s just my opinion.)The other significant difference between using
ScannerandBufferedReaderis thatScannerhides anyIOExceptions that might occur in a call tohasNext...()and returns simplyfalse. This is a good thing for typical use-cases ofScanneras a light-weight user input parser (as you are using it onkeyInput), but maybe not in other use-cases.