简体   繁体   中英

Java Program for infinite loop

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
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.

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);

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM