When I run the program in eclipse, I cannot break out of the while loop after the user enters a certain integer to move on and actually calculate the number of divisors it has and print it out with counts.
/*
* 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;
}
}
}
}
Look at your if
statement:
if (N < 0)
break;
You're breaking out of the loop if the user enters a negative number - but you want to break out if they enter a positive number:
if (N > 0)
break;
(I haven't looked at the rest of the code, but that's what's wrong with the while
loop.)
Alternatively, you could use:
int N = input.nextInt();
while (N < 0) {
System.out.println("That number is not positive. Please try again.: ");
N = input.nextInt();
}
Additionally, I'd recommend:
if
statements etc, even if the body is a single statementN
should either be n
, or ideally a more descriptive name) See more on this question at Stackoverflow