I\'m trying to make a little chat program for experimentation, but seeing as I\'m not the best Java programmer, I don\'t know how to separate a port from an IP where they are bo
First, you should check if the String contains a colon. Then, you can use String.split(String) and Integer.parseInt(String) with something like
String input = "127.0.0.1:8080"; // <-- an example input
int port = 80; // <-- a default port.
String host = null;
if (input.indexOf(':') > -1) { // <-- does it contain ":"?
String[] arr = input.split(":");
host = arr[0];
try {
port = Integer.parseInt(arr[1]);
} catch (NumberFormatException e) {
e.printStackTrace();
}
} else {
host = input;
}
System.out.printf("host = %s, port = %d%n", host, port);
Output is
host = 127.0.0.1, port = 8080