I am working on a Server Client program in Java, using Sockets.
I ask the user to input a series of integers, add them in an ArrayList and send them over to the server as an Object using ObjectOutputStream. The Server then receives the object.
I parse the object as an ArrayList and then I use a method to calculate what is the maximum number of the integers and return it as a string to the client.
I am using BufferedReader for the user input
In a sense what I need is a logic on how to:
To check for the users input, if it is not “Ok” or press Enter
The user should be able to add numbers separated by a space.
If then he presses Enter then should exit the loop and the numbers add at the array
I have so far:
BufferedReader integers = new BufferedReader(new InputStreamReader(System.in));
// send int 1, for the Max number option
pw.println(option);
System.out.println(br.readLine());
String x = integers.readLine();
if(integers!=null){
readInt(integers);
}
objectOut = new ObjectOutputStream(client.getOutputStream());
objectOut.writeObject(maxNum);
objectOut.flush();
System.out.println(br.readLine());
objectOut.close();
break;
The readIn method:
public static int readInt(BufferedReader stdIn) {
while (true) {
try {
String line = stdIn.readLine();
int value = Integer.parseInt(line);
return value;
} catch (java.lang.NumberFormatException e) {
;
} catch (IOException e) {
;
}
}
}
You can better handle this with
Scanner.BufferedReaderis quite old and deprecated.Or, if user is entering all those numbers in one line with some delimiter between them, say a whitespace (
), you can split the input and store in ArrayList..