对于此程序,我正在尝试将倍数从“ n”打印为“ max”。我遇到的问题是如何进行适当的循环以打印这些数字。
样本输入:
n = 3 max = 20
示例输出:
3
6
9
12
15
18
public class Average {
public static void printMultiples(int n, int max) {
while (n<=max) {
for (int i=1;;i++) {
System.out.println(n*i);
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a positive integer:")
int n = s.nextInt();
System.out.println("Enter a maximum positive integer:")
int max = s.nextInt();
printMultiples(n,max);
}
}
}
答案 0 :(得分:1)
这应该有效:
import java.util.Scanner;
public class Average {
public static void printMultiples(int n, int max) {
for (int i = 1; i <= max; i++) {
if (i % n == 0) {
System.out.println(i);
}
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter a positive integer:");
int n = s.nextInt();
System.out.println("Enter a maximum positive integer:");
int max = s.nextInt();
printMultiples(n, max);
}
}
或使用Java 8 Lambda:
public static void printMultiples(int n, int max) {
IntStream.rangeClosed(1, max).filter(i -> i % n == 0).forEach(System.out::println);
}