【问题标题】:Checking if field is null检查字段是否为空
【发布时间】:2017-01-17 15:11:59
【问题描述】:

下面是我的代码,我正在尝试检查 xCoord 是否为空或为空,因此我可以抛出异常。我该怎么做? 我尝试使用 try/catch if xCoord == null 但这不起作用。

String x = JOptionPane.showInputDialog("X Coordinate", "Enter an x coordinate");
int xCoord = Integer.parseInt(x);
String y = JOptionPane.showInputDialog("Y Coordinate", "Enter a y coordinate");
int yCoord = Integer.parseInt(y);
String width = JOptionPane.showInputDialog("Radius", "Enter the length of the radius");
int radius = Integer.parseInt(width);

【问题讨论】:

  • 只有Objects可以为空
  • int 永远不能为空,请改用Integer 或检查x == null 等。

标签: java if-statement exception null


【解决方案1】:

一旦您拥有xCoord,就为时已晚。在尝试解析它之前,您需要检查x

String x = JOptionPane.showInputDialog("X Coordinate", "Enter an x coordinate");
if (x == null || x.length() == 0) {
    // Throw a meaningful exception
}
int xCoord = Integer.parseInt(x);

【讨论】:

    【解决方案2】:

    xCoordint,它是一个原始类型。基元不能是nulls。它们是为引用类型保留的。

    您可以做的是检查x 是否为空。是真的吗?是的,它可以。如果用户不点击OK(取消,esc,X),它将是null

    所以检查它的正确方法是:

    String x = JOptionPane.showInputDialog("X Coordinate", "Enter an x coordinate");
    if (x == null || x.isEmpty()) {
        //throw Exception or set x to "0" - I'll set to 0
        x = "0";
    }
    int xCoord = Integer.parseInt(x);
    

    【讨论】:

      【解决方案3】:

      xCord 是一个int,它是一个本机类型,不能为空。从不。

      只有对象引用可以为空(例如,如果 xCord 被定义为 Integer xCord)。

      【讨论】:

        猜你喜欢
        • 2012-02-21
        • 2011-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多