0

I'm trying to print out the value of adding between an integer and a double, however, one of the values is extremely long - What is the explanation for this as everything else seems fine? For example:

public static void main(String[] args) {
    double[] b = new double[] {
        0.62,
        0.54,
        0.78
    };
    int[] a = new int[] {
        2,
        5,
        7
    };

    for (int i = 0; i < b.length; i++) {
        for (int j = 0; j < a.length; j++) {
            System.out.println(b[i] + a[j]);
        }
    }
}

#output:

2.62
5.62
7.62
2.54
5.54
7.54
2.7800000000000002 //Why is this so long, and where did the last 2 come from?
5.78
7.78

And secondly, when I try to store the above into a double array, why won't it output correctly?

public static void main(String[] args) {
    double[] b = new double[] {
        0.62,
        0.54,
        0.78
    };

    int[] a = new int[] {
        2,
        5,
        7
    };

    double[][] c = new double[][] {};

    for (int i = 0; i < b.length; i++) {
        for (int j = 0; j < a.length; j++) {
            c[i][j] = b[i] * a[j];
            System.out.println(c[i][j]);
        }
    }
}

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0 at test.project1/tested.project.testLoop.main(testLoop.java:17)

Lukasz Blasiak
  • 642
  • 2
  • 10
  • 16
Stackbeans
  • 273
  • 1
  • 16
  • [Is floating point math broken?](https://stackoverflow.com/q/588004) – Pshemo May 02 '21 at 12:12
  • `c` has lenght zero, therefore the java.lang.ArrayIndexOutOfBoundsException – Curiosa Globunznik May 02 '21 at 12:13
  • @NikolaiDmitriev How would I go about storing it into `c`, as I thought that by doing it the way I did I was actually storing them into an empty variable that can take these values? – Stackbeans May 02 '21 at 13:11
  • arrays work like rows of buckets, you can't put anything in a row of buckets of length zero. You need to create one which has some buckets, at least one `buckets = new int[1];`, then you can put something in the 1st bucket (which has index zero) `buckets[0] = 123;`. Put something in the second bucket (buckets[1], which doesn't exist) gives you another ArrayIndexOutOfBoundsException. You attempt to use an array off arrays, so this applies to sub-arrays too, so to speak. – Curiosa Globunznik May 02 '21 at 17:11

0 Answers0