我正在做一个学校项目,我有点受阻。 我期待构建一个javascript,询问用户1到20之间的数字,然后查找并列出该数字在0和100范围内的所有倍数。
目前看来是这样的:
public static void main(String[] args) {
Scanner lector = new Scanner(System.in);
System.out.println("*** Program start ***\n");
System.out.println("Insert number [integer, between 1 and 20]: ");
boolean okay = false;
while (!okay) {
int n1 = lector.nextInt();
lector.nextLine();
if (n1<1 || n1>20) {
System.out.print("Invalid number!\nplease try again [between 1 and 20]: ");
} else {
okay = true;
System.out.println("Number accepted!");
}
int i = 0;
while (i <= 100) {
System.out.println(i);
if ((n1%100) == 0) {
System.out.println(n1);
}
i = i + 1;
}
System.out.println("\n*** End ***");
}
}
}
我显然很擅长数学,因为我无法使公式发挥作用。
提前谢谢!
答案 0 :(得分:1)
public static void main(String[] args) {
Scanner lector = new Scanner(System.in);
System.out.println("*** Program start ***\n");
System.out.println("Insert number [integer, between 1 and 20]: ");
boolean okay = false;
while (!okay) {
int n1 = lector.nextInt();
lector.nextLine();
if (n1<1 || n1>20) {
System.out.print("Invalid number!\nplease try again [between 1 and 20]: ");
} else {
okay = true;
System.out.println("Number accepted!");
}
int i = 0;
while (i <= 100) {
System.out.println(i);
if ((n1%i) == 0) {
System.out.println(i);
}
i = i + 1;
}
System.out.println("\n*** End ***");
}
}
}
答案 1 :(得分:0)
public static void main(String[] args) {
Scanner lector = new Scanner(System.in);
System.out.println("*** Program start ***\n");
System.out.println("Insert number [integer, between 1 and 20]: ");
boolean okay = false;
while (!okay) {
int n1 = lector.nextInt();
lector.nextLine();
if (n1<1 || n1>20) {
System.out.print("Invalid number!\nplease try again [between 1 and 20]: ");
} else {
okay = true;
System.out.println("Number accepted!");
}
int i = 0;
while (i <= 100) {
System.out.println(i);
if ((n1*i) <= 100) {
System.out.println(i);
}
i = i + 1;
}
System.out.println("\n*** End ***");
}
}
}
这应该有效。您只是发现数字n1
是否可以被100整除。
答案 2 :(得分:0)
所有倍数介于0和100之间?这就是for-loops的用途。执行IO并读取数字n1
后,将while循环更改为以下内容。
for (int i = n1; i >= 0 && i <= 100; i = i + n1) {
System.out.println(i);
}
如果你不熟悉for循环,这基本上说,将i
设置为n1
的值,并继续向其添加n1
,打印每个值当你去时。当它离开0..100的范围时,它终止。因此,例如,如果输入8,则为8,16,24,32,...,80,88,96。
如果您真的想使用while循环,请尝试:
int i = n1;
while(i >= 0 && i <= 100) {
System.out.println(i);
i = i + n1;
}