Reputation: 7855
if (!(portField.getText().equals(""))) {
String p = portField.getText();
CharSequence numbers = "0123456789";
if (p.contains(numbers)) {
listener = new ServerSocket(Integer.parseInt(p));
while (true) {
Socket socket = listener.accept();
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("Hi there, human.");
} finally {
socket.close();
}
}} else {
JOptionPane.showMessageDialog(null, "Only numbers are allowed.");
}
} else {
JOptionPane.showMessageDialog(null, "Please input a port.");
}
The problem is: The JOptionPane
pops up saying "Only numbers are allowed" even when I put numbers in the portField
. The CharSequence
and the way I've tested it to allow only numbers to be input, as far as I know, is correct, and Java ignores the whole block and jumps to the else
clause.
Why is this happening? Should I not use else
and use else if
instead?
Upvotes: 0
Views: 114
Reputation: 9609
contains
means contains the whole 0123456789
. For example: "a0123456789b"
Use p.matches("[0-9]*");
instead.
Upvotes: 8