Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 检查字段是否为空_Java_If Statement_Exception_Null - Fatal编程技术网

Java 检查字段是否为空

Java 检查字段是否为空,java,if-statement,exception,null,Java,If Statement,Exception,Null,下面是我的代码,我试图检查xCoord是否为null或空,以便抛出异常。我该怎么做? 如果xCoord==null,我尝试使用try/catch,但这不起作用 String x = JOptionPane.showInputDialog("X Coordinate", "Enter an x coordinate"); int xCoord = Integer.parseInt(x); String y = JOptionPane.showInputDialog("Y Coordinate",

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

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);

xCoord
是一种基本类型的
int
。原语不能为
null
s。它们是为引用类型保留的

您可以做的是检查
x
是否为空。会吗?是的,它可以。如果用户没有单击“确定”(取消,esc,X),则它将为空

因此,正确的检查方法是:

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);

xCoord
是一种基本类型的
int
。原语不能为
null
s。它们是为引用类型保留的

您可以做的是检查
x
是否为空。会吗?是的,它可以。如果用户没有单击“确定”(取消,esc,X),则它将为空

因此,正确的检查方法是:

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);

xCord
是一个
int
,它是本机类型,不能为null。从来没有


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

xCord
是一个
int
,它是一个本机类型,不能为null。从来没有


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

一旦你有了
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);

一旦你有了
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);

只有
对象
可以为空
int
不能为空,请改用
Integer
或检查
x==null
等。只有
对象
可以为空
int
不能为空,改用
Integer
或检查
x==null
等。