0
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.");
}

问题是:JOptionPane即使我在portField. 据CharSequence我所知,我测试它只允许输入数字的方式是正确的,Java 会忽略整个块并跳转到else子句。

为什么会这样?我不应该使用else和使用else if吗?

4

1 回答 1

8

contains意味着包含整体0123456789。例如:"a0123456789b"

改为使用p.matches("[0-9]*");

于 2013-06-30T00:50:04.010 回答