Java:创建方法来打印 1 和 n 之间的所有 3 的倍数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21409329/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Create method to print all multiples of 3 between 1 and n?
提问by user3245026
So the question is asking to create a method that will take an integer x as a parameter and print out all integers from 0->x that are multiples of three.
所以问题是要求创建一个方法,该方法将一个整数 x 作为参数并打印出 0->x 中的所有整数,它们是三的倍数。
I can print out the number of times three divides x like so:
我可以像这样打印出三除 x 的次数:
public int Threes(int x){
int i = 0;
for(int counter = 1; counter <= x; counter++){
if (counter % 3 ==0){
i ++;
}
}
return i;
but I'm not sure how to print out each multiple of 3!?
但我不确定如何打印出每个 3 的倍数!?
回答by Matt
for(int counter = 1; counter <= x; counter++){
if (counter % 3 ==0){
System.out.println(counter);
}
}
回答by jonhopkins
An even quicker approach would be to increment by 3
更快的方法是增加 3
public void Threes(int x) {
for (int counter = 3; counter <= x; counter = counter + 3) {
System.out.println(counter);
}
}
This loop will jump right to the multiples of 3, instead of counting every single number and having to do a modulo check for each iteration. Since we know that 1 and 2 are not multiples of 3, we just skip right to 3 at the beginning of the loop. If the input happens to be less than 3, then nothing will be printed. Also, the function should be void
since you're printing instead of returning anything.
这个循环将直接跳到 3 的倍数,而不是计算每个数字并且必须对每次迭代进行模检查。因为我们知道 1 和 2 不是 3 的倍数,所以我们在循环开始时直接跳到 3。如果输入恰好小于 3,则不会打印任何内容。此外,该功能应该是void
因为您正在打印而不是返回任何内容。
(Your title says 1 to n
, but your question says 0 to n
, so if you actually need from 0 to n
, then change the declaration of counter
to int counter = 0;
)
(你的标题说1 to n
,但你的问题说0 to n
,所以如果你真的需要 from 0 to n
,那么改变counter
to的声明int counter = 0;
)
回答by ssempijja dauglas
Best practice using the For-loop in Java.
在 Java 中使用 For 循环的最佳实践。
public class MultiplesOfThree {
public static void main(String []args){
for (int m = 1; m<=12; m++){
System.out.println(m*3);
}
}
}
回答by Lance Johnson
Jason Aller wow that was so simple and elegant. This one builds on it by counting down from 300 to 3, by 3's.
Jason Aller 哇,这太简单和优雅了。这个建立在它的基础上,从 300 倒数到 3,以 3 为单位。
public class byThrees {
public static void main(String[] args) {
for (int t = 100; t >= 0; t--) {
System.out.println(t*3);