【发布时间】:2014-11-08 04:39:19
【问题描述】:
当我检查数组的长度是否等于 0 时,我得到了 NullPointerException,但我找不到它为什么不工作的原因。谁能告诉我我做错了什么? 这是我的整个函数代码:
public static ArrayList<String> searchZone(Player p){
openConnection();
ArrayList<String> data = new ArrayList<String>();
WorldEditPlugin worldEdit = (WorldEditPlugin) Bukkit.getServer().getPluginManager().getPlugin("WorldEdit");
Selection selection = worldEdit.getSelection(p);
String query = "SELECT * FROM " + db + ".blocks";
ArrayList<String> res = executeQueryWe(query);
String[] items = res.toArray(new String[res.size()]);
int i = 0;
int iters = items.length;
while(i < iters){
try{
if(selection != null){
String[] locs = items[i].split(",");
World world = Bukkit.getServer().getWorld(locs[0]);
int x = Integer.valueOf(locs[1]);
int y = Integer.valueOf(locs[2]);
int z = Integer.valueOf(locs[3]);
Location loc = new Location(world, x, y ,z);
if(selection.contains(loc)){
String query2 = "SELECT * FROM `blocks` WHERE `world`='" + world.getName() + "' AND `x`='" + x + "' AND `y`='" + y + "' AND `z`='" + z + "';";
data = executeQuery(query2);
}
}
} catch(Exception e){
closeConnection();
p.sendMessage(prefix + ChatColor.RED + "An error occured while reading database");
break;
}
p.sendMessage(prefix + ChatColor.RED + "Please make a selection first");
break;
}
if(data.size() != 0){ //<---------------------------- ERROR COMES FROM HERE
closeConnection();
return data;
} else {
data.add("No entries has been found.");
closeConnection();
return data;
}
}
【问题讨论】:
-
这表明
executeQuery(query2)正在返回null。如果我是你,我会检查这个,如果是真的,你需要做一些调查来找出原因。 -
详细说明@HovercraftFullOfEels 所说的内容。因为 executeQuery 返回 null 你不能调用
.size()因为 data 不是一个数组列表它是 null。如果您确保数据不为 NULL,则此测试将起作用,否则更改测试以查看数据本身是否为空 -
没错,但即使使用
if(!data.equals(null) || !data.isEmpty() || data.size() != 0){,它也会给我一个 nullPointerException -
哎呀,你从不使用
if (foo.equals(null))检查空值,因为这总是会失败,因为你会在空值上调用一个方法。再次从不这样做。你总是使用if (foo == null)或if (foo != null)。 -
不知道,谢谢提示
标签: java arrays nullpointerexception bukkit