Java 检查字段是否为空
下面是我的代码,我试图检查xCoord是否为null或空,以便抛出异常。我该怎么做? 如果xCoord==null,我尝试使用try/catch,但这不起作用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",
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
等。