【问题标题】:Safeguard a String from being null in JTextfield using if-else使用 if-else 防止字符串在 JTextfield 中为空
【发布时间】:2019-12-19 20:20:19
【问题描述】:

我是 Java 新手。我想提醒我的用户,如果他们没有在JTextField 中输入String,所以我使用if-else 语句来保护。但是,当我测试它时,提醒并没有跳出来。

如何使用 if-else 语句保护文本字段中的字符串不为空?

if ( !name == null && score >= 0) {
    Student stu = new Student(name, score);
    students.add(stu);
    }
}
else if(name == null) {
    reminder.setText("Could you tell me your name?");
}
else{
    reminder.setText("Enter numbers for score! Must be a positive number!");
}

【问题讨论】:

  • 你的问题不清楚
  • 大括号/格式没有意义。单独检查 name 是否为 null 不会捕获空值 - 也就是说,name 可能包含空字符串 ""
  • !name == null 应该写成name != null
  • 请澄清:上下文是什么,您使用的框架,您如何获得名称,提醒类型等。如果您正确格式化代码也会更好。

标签: java swing jtextfield


【解决方案1】:

空检查是if (object != null),如果你想检查一个文本字段是否被填写,

JTextField field = new JTextField();
String text = field.getText();
if (text != null && text.length() > 0) {
    System.out.println("Field has data");
}

【讨论】:

    猜你喜欢
    • 2015-09-23
    • 1970-01-01
    • 2014-05-20
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 2019-04-18
    • 2016-05-15
    相关资源
    最近更新 更多