简体   繁体   中英

I keep getting an infinite do while loop

I wrote a program that can catch a user input error.

When I try to make my program do a "do over" (with a do while loop) it runs into an error. The program (instead of restarting with the user input through the scanner) will print the System.out.println lines from exception catch block over and over.

Below is my code and I really hope that somebody can help me with it.

    int x = 0;
    int y = 0;
    int Temp = 0;
    int Rest = 0 ;
    int Works = 1;

    Scanner s = new Scanner(System.in);

    do{
    try{

    System.out.println("Bitte geben sie zwei Nummern ein für den ggT.");
    System.out.print("Die erste Nummer: ");
    x = s.nextInt();

    System.out.print("Die zweite Nummer: ");
    y = s.nextInt();

    if (x < y){
        Temp = x;
        x   = y;
        y = Temp;
        }System.out.println("Berechnung des ggT von " +x +" und " +y +".");

        do{
        System.out.println("Rechne " +x +" mod " +y +": ");
        Rest = x % y;
        if (Rest != 0){
            x = y;
            y = Rest;
        }
        }while (Rest !=0);
    System.out.println("Der größte gemeinsame Teiler lautet: " + y);    
    Works=2;    
    }
    catch(Exception e){
            System.out.println("Sie dürfen nicht durch Null (0) teilen.");
            System.out.println("Sie dürfen keine Dezimalzahlen benutzen.");
            System.out.println("Sie dürfen keine Zeichen benutzen.");
            System.out.println("Versuchen wir es noch einmal :)");
        }
}while(Works==1);
}

It will print

Bitte geben sie zwei Nummern ein für den ggT.
Die erste Nummer: 
Sie dürfen nicht durch Null (0) teilen.
Sie dürfen keine Dezimalzahlen benutzen.
Sie dürfen keine Zeichen benutzen.
Versuchen wir es noch einmal :)

over and over. Instead of waiting for user input.

I hope that the German as well as my code is not to off putting.

Try to advance the Scanner to the next line by calling the nextLine() method on your Scanner s in your catch block. This should clear the input.

catch(Exception e){
        System.out.println("Sie dürfen nicht durch Null (0) teilen.");
        System.out.println("Sie dürfen keine Dezimalzahlen benutzen.");
        System.out.println("Sie dürfen keine Zeichen benutzen.");
        System.out.println("Versuchen wir es noch einmal :)");
        s.nextLine();   // Advance Scanner to the next line
    }

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