I am doing the 100 Doors problem as an exercise to practice user input and loops. I do understand the problem can be solved by outputting every square number up to the maximum number, but it defeats the purpose of the exercise. The 100 Doors problem goes like this:
\$N\$ doors are closed. In the first pass, I open all of them. In the second pass, I toggle every second door. In the third pass, I toggle every third door. I continue this until I have completed the \$N\$th pass. Find all the doors that will remain open after \$N\$ passes.
Here is the code:
import java.io.IOException;
import java.util.Scanner;
public class hundredDoors {
static boolean hasNum = false;
public static void main(String[] args) throws IOException {
while (!hasNum) {
Scanner input = new Scanner(System.in);
int numOfDoors = 0;
System.out.print("Please enter the number of doors: ");
if (input.hasNextInt()) {
hasNum = true;
numOfDoors = input.nextInt();
if (numOfDoors < 1) {
hasNum = false;
System.out.println("Please enter an integer.");
continue;
}
boolean[] doors = new boolean[numOfDoors];
for (boolean door : doors) {
door = false;
}
for (int index = 1; index <= numOfDoors; index++) {
for (int door = index - 1; door <= numOfDoors - 1; door += index) {
doors[door] = !doors[door];
}
}
String output = "Doors still opened: \n";
int loops = 0;
for (int door = 0; door <= numOfDoors - 1; door++) {
if (loops == 10) {
output += "\n";
loops = 0;
}
if (doors[door]) {
output += (door + 1 + " ");
loops += 1;
}
}
input.close();
System.out.println(output);
}
else {
System.out.println("Please enter an integer.");
}
}
}
}
One note for this program is that \$N\$ is supplied by the user. The other is that for formatting sakes, each line will have a maximum of 10 numbers (# of door).
My question here isn't how to make it more efficient (the most efficient method is to output every square since they have an odd number of factors as explained here) but rather if the code can be more clean/clear (ie, names of indentifiers, loops can be shortened, input validation check can be better, etc).
input.nextInt()
result is discarded. \$\endgroup\$