首页 > 解决方案 > Print 4 numbers (that are divisible by 3 and 6) before x and store them in an array

问题描述

I wanted to print 4 numbers (that is divisible by 3 and 6) before x and store it in an array. For example, if I input 29 the code will print 6 12 18 24.

My code so far which doesn't even work:

int array[] = new int[4];
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int x = sc.nextInt();
for (int counter = 1; counter <= x; counter++) {
    if (counter % 3 == 0 && counter % 6 == 0) {
        for (int i = 0; i < array.length; i++) {
            array[i] = counter;
            System.out.println(array[i]);
        }
    }
}

标签: javaarraysfor-loopif-statementnumbers

解决方案


There were 2 problems. First you were adding extra unnecessary loop when your condition was true for division check and second you were starting your loop from 1 to x while your expected output is to check the divisibility from x to 1. Here's the fix:

int array[] = new int[4];
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int x = sc.nextInt(), i = 0;
System.out.println(x);
for (int counter = x - 1; counter > 0; counter--) {
    if (counter % 3 == 0 && counter % 6 == 0) {
        array[i] = counter;
        System.out.println(array[i]);
        i++;
        if (i == 4) {
            break;
        }
    }
}

Check: https://ideone.com/5HYhsT


推荐阅读