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