Search code examples
javaloopswhile-looploading

How to end a infinite while loop with user input


I am trying to create a loading sequence of 3 dots that repeats itself until input from the user breaks the loading sequence specifically the enter key. i connot for the life of me get the infinite while loop to end with input

public class loop {

    public static void AnyKey() {
        try {
            System.in.read();
            loading(false);
        } catch (Exception e){}
    }

    public static void pause(long duration) {
        try{
            Thread.sleep(duration);
        } catch (InterruptedException e){}
    }

    public static void loading(boolean status){
        if (status == true) {
            while (status) {
                pause(500);
                int i;
                for (i = 0; i <3; i++){
                    System.out.print(".");
                    pause(500);
                }
                System.out.print("\b\b\b");
            }
        }
    }

    public static void main(String[] args) {
        loading(true);
        AnyKey();
    }
}

Solution

  • I figured it out i needed to learn about and use Threads and global variables check out my code below im fairly pleased with myself i was working on this for 3 days now lol

        import java.util.Scanner;
    
    class AnyKey extends Thread {
    
        public void run() {
            Scanner scanner = new Scanner(System.in);
            scanner.nextLine();
            loadingDots.loadingStatus = false;
        }
    }
    public class loadingDots {
        public static boolean loadingStatus;
        public static void pause(long duration) {
            try {
                Thread.sleep(duration);
            } catch (InterruptedException e) {}
        }
        public static void loading(){
            loadingStatus = true;
            while (loadingStatus) {
                pause(500);
                int i;
                for (i = 0; i < 3; i++) {
                    if (!loadingStatus){
                        break;
                    }
                    System.out.print(".");
                    pause(500);
                }
                System.out.print("\b\b\b");
            }
        }
    
        public static void main(String[] args) {
            AnyKey anykey = new AnyKey();
            anykey.start();
            loading();
        }
    }