We know that nextInt()
, nextDouble()
, nextLine()
, etc methods of Java Scanner
class parses something (int, double, line, etc) and advances the position of the scanner. But I need a way only for parsing something but not for advancing the position. That means, I need some way for something like peekInt()
, peekDouble()
, peekLine()
, etc methods.
Here is an example for why it may be necessary. Suppose, I have an abstract class Server
which has an abstract method respond(Scanner in, PrintWriter out, String clientIp)
to be implemented by other classes. Here is the portion of code:
public abstract class Server {
// ... (some initialization variables)
public static final String endSocketMarker = "END";
public final void runServer() {
// ... (multithreading code)
clientSocket = serverSocket.accept();
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(clientSocket.getInputStream())));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String clientIp = in.nextLine();
String marker = "";
do {
respond(in, out, clientIp); // call abstract method
marker = in.nextLine(); //TODO: find a way so that input line is peeked (but not skipped)
} while(!marker.equals(endSocketMarker));
// ... (close client socket)
}
protected abstract void respond(Scanner in, PrintWriter out, String clientIp);
// ... (other methods)
}
Here marker = in.nextLine();
parses the line until a line separator found and then advances the position to the beginning of the next line. If marker.equals(endSocketMarker)
is false, then the string assigned in marker
cannot be read inside respond(in, out, clientIp)
method at all. It must be avoided somehow. I may pass the variable marker
into respond(in, out, clientIp)
, but it will make the code cluttered.
Is there any better way for achieving my goal?