简体   繁体   中英

How to create a single array from for loop values

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number: ");
        int a = sc.nextInt();
        for ( int i = 1; i < a; i++) {
            int []div = {a/i};
            if (a%i == 0 ) System.out.print(Arrays.toString(div) + " ");
        }
}

Input: 68 Output : [68] [34] [17] [4] [2]

Question is how to make a single array so it looks like [68, 34, 17, 4, 2] ?

Since you can't calculate how many elements the div will have in advance (it requires factorization of a ), you have several options:

1. Calculate the size of div as a separate step:

int a = 68;
int n = 0; // length of the result
for (int i = 1; i < a; i++) {
    if (a % i == 0) {
        n++;
    }
}
int[] div = new int[n];
n = 0;

for (int i = 1; i < a; i++) {
    if (a % i == 0) {
        div[n++] = a / i;
    }
}
System.out.println(Arrays.toString(div));

2. Use mutable growing collection instead of the array:

int a = 68;
List<Integer> div = new ArrayList<>();
for (int i = 1; i < a; i++) {
    if (a % i == 0) {
        div.add(a / i);
    }
}
System.out.println(div);

If you need, you can convert the collection to the primitive array afterwards:

int[] divArr = div.stream().mapToInt(Integer::intValue).toArray();
System.out.println(Arrays.toString(divArr));

3. One-liner using Stream :

As @Eritrean suggested in the comments, you can use IntStream to build your array:

int a = 68;
int[] div = IntStream
    .range(1, a)
    .filter(i -> a % i == 0)
    .map(i -> a / i)
    .toArray();
System.out.println(Arrays.toString(div));

It will be more efficient than the second variant, as it avoids creating Integer wrappers.


PS I omitted main method and Scanner initialization for brevity. You can put it back, if you need, for example:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number: ");
    int a = sc.nextInt();
    int n = 0; // length of the result
    for (int i = 1; i < a; i++) {
        if (a % i == 0) {
            n++;
        }
    }
    int[] div = new int[n];
    n = 0;

    for (int i = 1; i < a; i++) {
        if (a % i == 0) {
            div[n++] = a / i;
        }
    }
    System.out.println(Arrays.toString(div));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM