1

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

PM 77-1
  • 11,712
  • 18
  • 56
  • 99
Forcio
  • 13
  • 3

1 Answers1

0

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
    }
darron614
  • 783
  • 5
  • 14
  • Thank you so much :) This has fixed my problem I would upvote your answer but am lacking the karma to do so. So I will just have to say thank you again, this drove me nuts yesterday! – Forcio Jan 14 '17 at 17:19