Stiller77 Stiller77 - 7 months ago 7
Java Question

How can I make this program running correctly?

I want to write a java program that reads two integer numbers from the user,
and then displays all the numbers from the first number to the
second number that are divisible by 5 or 6, but not both. The
output should be displayed as ten numbers per line. This is what I got but it's not working .. can someone help?

public class Testing {
static int num1;
static int num2;
public static void main(String[] args) {

userInput();
factorial();

}

public static void userInput() {
Scanner sc = new Scanner(System.in);

System.out.println("Enter first number: ");
num1 = sc.nextInt();

System.out.println("Enter second number: ");
num2 = sc.nextInt();
}

public static void factorial() {
int n;
int counter = 0;

for (n = num1; n <= num2; n++) {
if ((n % 5 == 0 && n % 6 != 0) || (n % 6 == 0 && n % 5 != 0)) {
System.out.print(n + " ");

counter = counter++ % 10;
if (counter == 9) {
System.out.println();
}

}
}
}
}


If I enter these integers:

Enter first number:
5
Enter second number:
90


The program displays that I want 10 per line..

5 6 10 12 15 18 20 24 25 35 36 40 42 45 48 50 54 55 65 66 70 72 75 78 80 84 85

Answer

Your issue is your counter variable. Since you only want 10 results per line, once counter is greater than or equal to 9 you should break the line with a Println() and then make sure your counter is set back to 0. See code below:

public static void factorial() {
int n;
int counter = 0;

for (n = num1; n <= num2; n++) {
    if ((n % 5 == 0 && n % 6 != 0) || (n % 6 == 0 && n % 5 != 0)) {
        System.out.print(n + " ");

        counter++;
        if (counter >= 9) {
            System.out.println();
            counter = 0;
        }

    }
}