我目前正在尝试添加位于字符串数组中多个字符串中的所有双精度数的总和。我想要分割它们,就像你在屏幕截图中看到的一样,但它不让我。有人可以让我知道我做错了什么,如果有一个更简单的方法去做。谢谢:))
package javaapplication3;
public class JavaApplication3 {
public static void main(String[] args) {
String [] testArray = new String [2];
testArray[0] = "Part1: $10.00";
testArray[1] = "Part2: $30.00";
testArray[3] = "Part3: $50.00";
Double [] array = new Double[testArray.length];
for(int i=0;i<testArray.length;i++){
//I want this to iterate through testArray[i], split every string by $,
//then store my doubles in array[i], so that I can add them and get total cost
//In real project there are like 50 parts I need to add together.
array[i] = Double.valueOf(testArray[i].split("$")[1]);
}
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at javaapplication3.JavaApplication3.main(JavaApplication3.java:7)
C:\Users\Micha\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
答案 0 :(得分:0)
问题在于testArray中的索引。它已超出范围,你已经为它分配了三个长度,并且你正在为索引3添加一个超出范围的值。
数组从零开始,所以如果你的大小为3则意味着0,1,2。并且你有testArray[3] = "Part 3: $ 50 "
这意味着你分配出界。请改为testArray [2] = "Part 3: 50"
。