Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从字符串数组中的字符串添加双精度?_Java_Arrays_String_Double - Fatal编程技术网

Java 如何从字符串数组中的字符串添加双精度?

Java 如何从字符串数组中的字符串添加双精度?,java,arrays,string,double,Java,Arrays,String,Double,我目前正在尝试添加字符串数组中多个字符串中所有双精度的总和。我曾想过像你在截图中看到的那样拆分它们,但它不允许我这样做。有人能告诉我我做错了什么,有没有更简单的方法。谢谢: package javaapplication3; public class JavaApplication3 { public static void main(String[] args) { String [] testArray = new String [2]; tes

我目前正在尝试添加字符串数组中多个字符串中所有双精度的总和。我曾想过像你在截图中看到的那样拆分它们,但它不允许我这样做。有人能告诉我我做错了什么,有没有更简单的方法。谢谢:

   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)

问题在于testArray中的索引。它越界了,你给它指定了长度3,你给索引3加了一个越界的值。
数组从零开始,因此如果大小为3,则表示0,1,2。而你的testArray[3]=第3部分:$50,这意味着你的任务超出了范围。改为这样做testArray[2]=第3部分:50。

我这样做了,上面说我的代码的屏幕截图点击屏幕截图,你会看到图像$在正则表达式中是一个特殊字符,当我达到2时,你的代码将以NullPointerException失败。你有一个长度为3的数组……但试着引用第4个位置,即3