首页 > 解决方案 > 我以前有效的 if 语句不再有效

问题描述

我正在尝试创建一个 if else 语句,它一个接一个地检查多个值,以查看它们是否为空。

我之前创建的 if else 语句运行良好,但重新启动我的电脑后它不再工作。

任何帮助表示赞赏。

这是我的代码:

    //Declare Strings
    String ProjectNo, Location, VP;

    //Store values from text boxes into strings
    ProjectNo = txtProjectNum.getText();
    Location = txtLocation.getText();
    VP = txtVPNo.getText();


    if(ProjectNo == null){

        JOptionPane.showMessageDialog(null, "No fields can be left empty!");

    }

    else if (Location == null){

        JOptionPane.showMessageDialog(null, "No fields can be left empty!");

    }

    else if (VP == null){

        JOptionPane.showMessageDialog(null, "No fields can be left empty!");

    }

    else{

        JOptionPane.showMessageDialog(null, "All fields have been filled in!");

    }

标签: javaif-statementnetbeans

解决方案


我相当确定该getText方法永远不会返回null。如果要检查空字段,请选中.length() == 0.isEmpty。你可以.trim()先考虑。例如:

if (projectNo.trim().isEmpty()) {

或者也许trim在将文本放入变量时:

projectNo = txtProjectNum.getText().trim();
// ...
if (projectNo.isEmpty()) {

推荐阅读