在计算某个整数的除数的#时,我的程序无法突破'While Loop'?

Sha*_*haz -2 java for-loop if-statement while-loop integer-division

当我在eclipse中运行程序时,在用户输入某个整数后继续运行并实际计算它所具有的除数的数量并用计数打印出来之后,我无法摆脱while循环.

   /*
 * This program reads a positive integer from the user. 
 * It counts how many divisors that number has, and then it prints the result.
 * Also prints out a ' . ' for every 1000000 numbers it tests. 
 */

import java.util.Scanner;

public class forloopTEST1 {


public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    int N; //A positive integer entered by the user.
           //  Divisor of this number will be counted.

    int testDivisor;    // A number between 1 and N that is a possible divisor of N.

    int divisorCount;   // A number of divisors between 1 to N that have been found.

    int numberTested;   // Used to count how many possible divisors of N have been tested, When # reached 1000000
                        //a period is output and the value of numberTested is reset to 0.

    /* Get a positive integer from the user */

    while (true) {
        System.out.println("Enter a positive integer: ");
        N = input.nextInt();

        if (N < 0)
            break;
        System.out.println("That number is not positive. Please try again.: ");

    }

    /* Count divisor, printing ' . ' after every 1000000 tests. */

    divisorCount = 0;
    numberTested = 0;

    for (testDivisor = 1; testDivisor <= N; testDivisor++) {
    if ( N % testDivisor == 0 );
        divisorCount++;
        numberTested++;

    if (numberTested == 1000000) {
        System.out.println(".");
        numberTested = 0;

    }


    }

}

}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 10

看看你的if陈述:

if (N < 0)
    break;
Run Code Online (Sandbox Code Playgroud)

如果用户输入一个负数,你就会脱离循环- 但是如果他们输入一个数,你想要突破:

if (N > 0)
    break;
Run Code Online (Sandbox Code Playgroud)

(我没有看过剩下的代码,但这就是while循环的错误.)

或者,您可以使用:

int N = input.nextInt();
while (N < 0) {
    System.out.println("That number is not positive. Please try again.: ");
    N = input.nextInt();
}
Run Code Online (Sandbox Code Playgroud)

另外,我建议:

  • 始终对if语句等使用大括号,即使正文是单个语句
  • 在首次使用时声明局部变量,而不是在方法的顶部声明all
  • 遵循Java命名约定(N应该是n,或者理想情况下是更具描述性的名称)