Alexander Quilliam Alexander Quilliam - 3 months ago 11
Java Question

In Java, how can I store information from a for loop in an array?

How could I store the values in these two for-loops in a way that they could be added together later? The program is to find all of the multiples of 3 and 5 less than 1000 and add them together. I am using

IntStream
to add them, but it isn't working, it just returns all of the multiples of 3 and 5 unadded.

import java.util.stream.IntStream;

public class MultilplesOf3and5 {

public static void main(String[] args) {
int[] array = new int[1000];

for(double m = 999; m > 0; m--){
double div3 = m / 3;
if(div3 % 1 == 0){
array[(int) m] = (int) m;
int sum = IntStream.of((int) m).sum();
System.out.println(sum);
}
}

for(double f = 999; f > 0; f--){
double div5 = f / 5;
if(div5 % 1 == 0){
array[(int) f] = (int) f;
int sum = IntStream.of((int) f).sum();
System.out.println(sum);
}
}
}
}


EDIT:
I found a solution:

public class MultilplesOf3and5 {

public MultilplesOf3and5(){
double[] array = new double[1000];

for (double i = 0; i < array.length; i++){
double div3 = i / 3;

if(div3 % 1 == 0){
array[(int) i] = i;
}
}

int sum3 = 0;

for (double q : array)
sum3 += q;
System.out.println(sum3);

for (double f = 0; f < array.length; f++){
double div5 = f / 5;

if(div5 % 1 == 0){
array[(int) f] = f;
}
}

int sum5 = 0;

for (double q : array)
sum5 += q;
System.out.println(sum5);


int totalSum = sum3 + sum5;

System.out.println(totalSum);
}

public static void main(String[] args) {
new MultilplesOf3and5();
}
}

Answer

You can store values in an array by first instantiating an array:

int[] arrayName = new int[10];

then you have to store each item in the right index:

for(int i = 0; i < 10; i++){
    arrayName[i] = i;
}

that way the values are stored in your array.

Then you can print the contents of that array by looping through each item in that array:

for(int i = 0; i < 10; i++){
    System.out.println(arrayName[i]);
}

Or you can use the very handy array list in java.

Another solution is using the strongly typed ArrayList in java (generics):

ArrayList<Integer> arrayName = new ArrayList<Integer>();

for(int i = 0; i < 10; i++){
    arrayName.add(i);
}

then you can print one by one using the earlier for loop:

for(int i = 0; i < 10; i++){
    System.out.println(arrayName.get(i);
}