以下代码将字符串解析为字符串对象,并将值放入对象数组中。
对于任何表示数字的字符串,它会尝试用 Double 对象替换该字符串。但是我得到以下异常:
java.lang.ArrayStoreException:java.lang.Double
public class Main
{
public static void main(String[] args) throws Exception
{
String text = "one,two,123,123.45";
Object[] row = text.split(",");
for (int i = 0; i < row.length; i++)
{
try
{
row[i] = new Double( row[i].toString() );
}
catch(Exception e)
{
System.out.println(e);
}
}
System.out.println();
for(Object o: row)
System.out.println(o.getClass());
// This works, I don't see the difference?
Object[] data = new Object[2];
data[0] = "one";
data[1] = "111.22";
data[1] = new Double( data[1].toString() );
System.out.println();
for(Object o: data)
System.out.println(o.getClass());
}
}
知道我做错了什么吗?为什么第二种情况有效而第一种情况不起作用?
最佳答案
来自 ArrayStoreException
的文档
Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects. For example, the following code generates an ArrayStoreException:
Object x[] = new String[3];
x[0] = new Integer(0); //exception
在您的代码中,您也在做同样的事情。当你写
Object[] row = text.split(",");
这变成了一个字符串数组。后来你尝试做
row[i] = new Double( row[i].toString() );
由于 String
不是 Double
,因此引发异常。
关于java - 尝试用对象数组中的 double 值替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33967520/