I'm trying to Write the main method of a Java program that has the user enter two integers, i and n. If either integer is less than 2, output “Please enter numbers above 1.” Otherwise, output the n positive multiples of i, separated by spaces.
I'm close but can't figure out how to do display the multiples.
Here's what a sample run should look like:
Enter i: 4
Enter n: 6
6 multiples of 4 are: 8 12 16 20 24 28
import java.util.*;
public class HW5Problem3 {
public static void main (String [] args) {
int i = 0;
int n = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter i: ");
i = input.nextInt();
System.out.print("Enter n: ");
n = input.nextInt();
if ((i <= 1) || (n <= 1)) {
System.out.println("Please enter numbers above 1");
System.exit(1);
}
System.out.print(n + " multiples of " + i + " are: ");
}
}
答案 0 :(得分:1)
你需要创建一个循环(for循环或while循环)从2迭代到n + 1,并将i乘以你的循环变量,输出循环中的每个值
答案 1 :(得分:1)
n
是乘数,i
是因素,对吗?在编程中,乘数是循环最大值:
System.out.print(n + " multiples of " + i + " are: ");
for (int inc=1; inc<=n; inc++) {
System.out.print(" " + i*inc);
}
打印出来:4 8 12 16 20 24
如果你真的想把它作为输出:8 12 16 20 24 28复制/粘贴这一行:
for (int inc=2; inc<=(n+1); inc++)
答案 2 :(得分:1)
你可以在那个班级中使用以下方法
public static void mult(int i,int n){
int[] arr=new int[n];
int count=2;
for(int x=0;x<n;x++){
arr[x]=i*count++;
}
for(int y=0;y<arr.length;y++){
System.out.print(arr[y]+" ");
}
现在您的最终代码看起来像
import java.util.*;
public class HW5Problem3 {
private int i = 0;
private int n = 0;
public static void main(String[] args) {
int i = 0;
int n = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter i: ");
i = input.nextInt();
System.out.print("Enter n: ");
n = input.nextInt();
if ((i <= 1) || (n <= 1)) {
System.out.println("Please enter numbers above 1");
System.exit(1);
} else {
System.out.print(n + " multiples of " + i + " are: ");
mult(i, n);
}
}
public static void mult(int i, int n) {
int[] arr = new int[n];
int count = 2;
for (int x = 0; x < n; x++) {
arr[x] = i * count++;
}
for (int y = 0; y < arr.length; y++) {
System.out.print(arr[y] + " ");
}
}
}
答案 3 :(得分:1)
//fills matrix with matlab like syntax
macro_rules! mat {
[] => { MatrixXf::construct(Vec::new(), 0, 0) };
[ $( $x: expr ),* $(; $( $y: expr ),*)* ] => {{
let mut tmp_vec = Vec::new();
let mut rows = 0;
let mut inner_cols = 0;
$(
tmp_vec.push($x);
inner_cols += 1;
)*
let cols = inner_cols; // remember how many columns the first row has
rows += 1;
$(
inner_cols = 0;
$(
tmp_vec.push($y);
inner_cols += 1;
)*
assert!(inner_cols == cols); // check that the following rows have as many columns as the first row
rows += 1;
)*
MatrixXf::construct(tmp_vec, rows, cols)//fills MatrixXf fields
}}
}