java 如何检测数组中是否存在索引 (String[])
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17094432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to detect if a index exists in an array (String[])
提问by Jay Carr
I'm using the str.split("!")
to pull a string in half when there is an exclamation mark contained in the string. With the way the code is set up I will get a 1 index array if there is no exclamation mark and a 2 index array if there is one.
str.split("!")
当字符串中包含感叹号时,我使用 将字符串拉成两半。按照代码的设置方式,如果没有感叹号,我将得到一个 1 索引数组,如果有,我将得到一个 2 索引数组。
Code:
代码:
String file, macroName;
String[] fileAndMacro = string.split("!");
if(fileAndMacro[0] != null)
file = new File(fileAndMacro[0]);
if(fileAndMacro[1] != null)
macroName = fileAndMacro[1];
If I put in a string with an exclamation mark, it works. For example "test!string"
would return fileAndMacro[0] = "test"
and fileAndMacro[1] = "string"
.
如果我输入带有感叹号的字符串,它会起作用。例如"test!string"
将返回fileAndMacro[0] = "test"
和fileAndMacro[1] = "string"
。
The problem is when I don't have an exclamation mark (as some of you can probably tell from my code). I simply get an ArrayIndexOutOfBoundsException
. So, clearly a null check is not doing the trick. Which makes sense considering there can't be a null value in memory if no space has been allocated for the value to be stored in.
问题是当我没有感叹号时(你们中的一些人可能会从我的代码中看出)。我只是得到一个ArrayIndexOutOfBoundsException
. 所以,很明显,空检查并没有起到作用。考虑到如果没有为要存储的值分配空间,则内存中不可能有空值,这是有道理的。
Despite my understanding of this, I'm not sure how to check to see if that second index exists or not. How do I check to see if an index exists or not in real time?
尽管我对此有所了解,但我不确定如何检查第二个索引是否存在。如何实时检查索引是否存在?
回答by mrcaramori
You need to check length of your array, so:
您需要检查数组的长度,因此:
if(fileAndMacro.length > 1)
macroName = fileAndMacro[1];
By accessing an index that doesn't exist, you would be accessing some other space in memory which does not belong to your created array (actually created in the split()
method), that's why you get an exception.
通过访问不存在的索引,您将访问内存中不属于您创建的数组(实际上是在split()
方法中创建的)的其他一些空间,这就是您得到异常的原因。
回答by Sebastian Redl
Just test fileAndMacro.length
. If it is 2 or larger, there was at least one exclamation mark.
只是测试fileAndMacro.length
。如果是 2 或更大,则至少有一个感叹号。
回答by Prasad Kharkar
You can check the length of an array using its length property array.length
您可以使用数组的 length 属性检查数组的长度 array.length
if (array.length < 2){
//perform some operation you want
}