java - 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]);
}
}
}
解决方案
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
推荐阅读
- python - 在 SQLAlchemy 中填充表的最佳方法是什么?
- unit-testing - dart mockito 中的 argThat 和 captureThat 匹配器有什么区别?
- python - 访问从地理编码返回的深层嵌套字典的最佳方法是什么?
- nsight - 是否有任何分析器能够使用 openacc 程序识别被复制进出 GPU 的变量的名称
- node.js - 为什么“npm install -g grunt-cli”不能正常工作?
- matlab - 在matlab / octave中将带有变量的符号向量分离为基向量和标量
- android - 任务“:app:processPromoGoogleServices”执行失败。> 找不到与包名称匹配的客户端,即使所有文件夹和名称都匹配
- java - Spring Cloud Config Server - 刷新键的空数组
- frama-c - Eva 计算区间的方法 [frama-c]
- bash - 如何使用 Bash 删除不需要的文件/文件夹