0

I have to write a java program that computes the greatest common divisor of two positive integers. Program has to check for the positive integers only. My problem is that when I enter a negative integer and then a non-numeric string, my program stops running. Bellow is my code:

import java.util.Scanner;
class GCD {
    public static void main (String[] args){
        Scanner sc = new Scanner(System.in);
        int a, b, m, n, remainder;
        System.out.print("Enter a positive integer: ");
        while (!sc.hasNextInt()){
            System.out.print("Please enter a positive integer: ");
            sc.next();
        }
        a = sc.nextInt();
        while (a <= 0){
            System.out.print("Please enter a positive integer: ");
            a = sc.nextInt();
        }


        System.out.print("Enter another positive integer: ");
        while (!sc.hasNextInt()){
            System.out.print("Please enter a positive integer: ");
            sc.next();
        }
        b = sc.nextInt();
        while (b <=0){
            System.out.print("Please enter a positive integer: ");
            b = sc.nextInt();
        }

        m = a;
        n = b;
        while (n != 0){
            remainder = m%n;
            m = n;
            n = remainder;
        }
        System.out.println("The GCD of " +a+ " and " +b+ " is " +m);
    }
}
mok
  • 6,612
  • 3
  • 34
  • 59

4 Answers4

1

Try this:

import java.util.Scanner;
public class A {
    public static void main (String[] args){
        int a, b, m, n, remainder;
        a = validInput();
        b = validInput();
        m = a;
        n = b;
        while (n != 0){
            remainder = m%n;
            m = n;
            n = remainder;
        }
        System.out.println("The GCD of " +a+ " and " +b+ " is " +m);
    }

    static int validInput() {
        Scanner sc = new Scanner(System.in);
        while(true){
            System.out.print("Please enter a positive integer: ");
            String tmp = sc.next();
            if (tmp.matches("^\\d+$")) {
                return Integer.parseInt(tmp);
            }
        }
    }
}

I suggest you to make your programs more modular, as you can see it's benefits in a simple program like this.

mok
  • 6,612
  • 3
  • 34
  • 59
  • Why using strings?! the scanner has the method readInt(). so it tests on its own if the input is correct or not, you ve got just to look for its value if >0 or not. – Basti Apr 28 '14 at 07:59
  • @Basti> When you get the input as a `String` you can check it against various arbitrary conditions using a powerful tool called regular expression, whilst when you try to use `readInt()` you should be sure about many things. – mok Apr 28 '14 at 08:04
  • in the case of reading in a simple positive value, you can use this method, catch its thrown exception if thrown (inputmissmatch – Basti Apr 28 '14 at 08:15
0
/* prompt a */
String a = sc.next();

/* prompt b */
String b = sc.next();

if (isValid(a) && isValid(b)) {
    int ia = Integer.parseInt(a);
    int ia = Integer.parseInt(b);

    /* calculations and such */
}

boolean isValid(String num) {
    try {
        int i = Integer.parseInt(num);
        if (i < 0) {
            return false;
        }
    } catch (NumberFormatException e) {
        return false;
    }
    return true;
}
Andrew Vitkus
  • 797
  • 6
  • 9
0

In your first while you call next(), but in your second you use nextInt(). If you enter at the first time a negative Integer, you ll step to the next while with the nextInt(). So you ll get an exception if the user is entering a String with something else than numbers, because the scanner cant get the value of keys or something else. A smarter way would be to catch the exception and use it for a endless while like this:

while(true)
   System.out.print("Please enter a positive Number: ");
   try{
      a = sc.nextInt();
      if(a>-1){
         break;
      }
   }catch(Exception ignore){
   }
}

This code will run until the user enters a positive number. If he enters something else than numbers, the exception will come and will be ignored and the while will go on, if the number was not positive (bigger than -1 in this case) the while will not break.

Basti
  • 1,085
  • 9
  • 30
0

It shound work, even if i don't try it. I have just 2 advise as you look new in coding : -When you make code, try to use function. Normally, you should never copy/paste. -Try to put full name to your variable, particulary if you share your code on a forum, it would be more simple to people to understand what you did, and help you :)

     import java.util.regex.Pattern;
     import java.util.Scanner;
     class GCD {
        public static void main (String[] args){
          Scanner sc = new Scanner(System.in);
          int a, b, m, n, remainder;
          a=askInt();
          b=askInt();
          m = a;
          n = b;
          while (n != 0){
          remainder = m%n;
          m = n;
          n = remainder;
          }
          System.out.println("The GCD of " +a+ " and " +b+ " is " +m);
       }

     private int askInt(){
          System.out.print("Enter a positive integer: ");
          String tampon = sc.nextLine();
          while(!Pattern.matches("\p{Digit}",tampon)){
              System.out.print("Please enter a positive integer: ");
              String tampon = sc.nextLine();
          }
          return Integer.valueOf(tampon);
     }
  }
Eliott Roynette
  • 614
  • 5
  • 18