0

The below code accepts an integer and checks and prints if <5, or if divisible by 5, or if divisible by 3 or if divisible by both 3 and 5. but I want to put the code into infinite looping so that the console repeatedly asks me to enter an integer after printing the output. Here is my code so far:

import java.util.Scanner;
public class Q3c {
public static void main(String args[]) {
    System.out.println("Enter an integer ");
    Scanner input = new Scanner(System.in);

    int n = input.nextInt();
    if ((n%5 == 0) && (n%3 == 0)) {
        System.out.println("The number " + n + " is  divisible by 3 and 5");
    }
    else {
        if(n%5 == 0) {
              System.out.println(n + " is divisble by 5");
        }
        if(n%3 == 0) {
              System.out.println(n + " is divisble by 3");
        }
    }

    if (n < 5) {
        System.out.println(n + "is <5");
    }
    input.close();
}
}

demo output:

Enter an integer 5
5 is divisibe by 5

Enter an integer

3 Answers 3

4
while(true) {
    //do stuff
}

for(;;) {
    //do stuff
}

do {
    //stuff
}while(true);

All three of these are infinite loops. If you want to exit the infinite loop based on some user input (suppose 0), you can just add:

if(n == 0) {
    break;
}

where ever you want your loop to end if they have entered 0. This code snippet works for all three infinite loop variations.

Sign up to request clarification or add additional context in comments.

Comments

0
while(true) {
    //your code
    //code to manage program exit.
}

or

for(;;) {
    //your code
    //code to manage program exit.
}

or

do {
    //your code
    //code to manage program exit.
}while(true);

Comments

0

I'd suggest using else if constructs, in your case, just to simplify the code... Something like:

Scanner input=new Scanner(System.in);
while(true) {
    System.out.println("Enter an integer ");
    int n=input.nextInt();
    if((n%5==0)&&(n%3==0)){
       //stuff
    } else if (n%5==0) {
       //other stuff
    } else if (n%3==0) {
       //other
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.