简体   繁体   English

Java忽略布尔值评估

[英]Java is ignoring a boolean evaluation

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 . 问题是:即使我在portField输入数字,也会弹出JOptionPane并说“仅允许数字”。 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. 据我所知, CharSequence和我测试它只允许输入数字的方式是正确的,Java忽略了整个块并跳转到else子句。

Why is this happening? 为什么会这样呢? Should I not use else and use else if instead? 如果我不使用else和使用else if呢?

contains means contains the whole 0123456789 . contains包含整个0123456789 For example: "a0123456789b" 例如: "a0123456789b"

Use p.matches("[0-9]*"); 使用p.matches("[0-9]*"); instead. 代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM