[英]Multiple Conditions Java Loop
So I'm learning Java by myself and I would like to create a program that returns the divisors of a number N in a given interval [A, B]. 因此,我自己学习Java,我想创建一个程序,该程序在给定间隔[A,B]中返回数字N的除数。 Here's my code 这是我的代码
Scanner in = new Scanner(System.in);
int n, a, b;
System.out.print("A: ");
a = in.nextInt();
System.out.print("B: ");
b = in.nextInt();
System.out.print("N: ");
n = in.nextInt();
System.out.printf("The divisors of %d in the interval [%d, %d] are: ", n, a, b);
for (int i = 1; i <= n & i < b; ++i){
if (n % i == 0){
System.out.println(i + " ");
}
}
Here's the problem: when I put a < i & i < b in the for condition, the program doesn't work. 这是问题所在:当我在for条件中放入<i&i <b时,该程序无法正常工作。 I've read it that Java is short-circuiting, but can I fix my code or should I use a while or something like that? 我已经读过Java在短路,但是我可以修复我的代码还是应该使用一段时间或类似的东西?
The logical AND operator in Java is &&
, not &
, the latter which is the bitwise AND operator. Java中的逻辑AND运算符是&&
,不是&
,后者是按位 AND运算符。 But, you don't even need the condition a <= i && i <= b
, because you can simply initialize the loop variable to a
: 但是,您甚至不需要条件a <= i && i <= b
,因为您可以简单地将循环变量初始化为a
:
for (int i=a; i <= b; ++i) {
if (n % i == 0) {
System.out.println("Found divisor: " + i);
}
}
Tim's answer above is a great answer, but you also asked about if you could/should do this as a while
loop. 上面Tim的答案是一个很好的答案,但您还询问是否可以/应该在while
循环中这样做。 If you wanted to use a while
loop, a simple implementation would be 如果您想使用while
循环,一个简单的实现就是
while (a <= b) {
if (n % a == 0) {
System.out.println("Found divisor: " + a);
}
a++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.