Created
January 30, 2013 05:17
-
-
Save pajuey/4670837 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* GCD.java | |
* Steven Pajuelo | |
* spajuelo | |
* pa3 | |
* Make a GCD to find GCD for two integer types, which neither are negative or of another type. | |
*/ | |
import java.util.Scanner; | |
public class GCD { | |
private static int divisor, dividend, gcd; | |
private static Scanner scan = new Scanner(System.in); | |
public static void main(String[] args) { | |
// Ask for dividend | |
System.out.print("Enter a positive integer: "); | |
Boolean cont = true; | |
// check type and save if int type | |
checkType(scan); | |
dividend = scan.nextInt(); | |
// compare, to discard negative numbers for dividend and divisor | |
while (cont) { | |
if(dividend > 0) { | |
System.out.print("Enter another positive integer: "); | |
checkType(scan); | |
divisor = scan.nextInt(); | |
} | |
if(dividend < 0) { | |
System.out.print("Please enter a positive integer: "); | |
checkType(scan); | |
dividend = scan.nextInt(); | |
} | |
if(divisor < 0) { | |
System.out.print("Please enter a positive integer: "); | |
checkType(scan); | |
divisor = scan.nextInt(); | |
} | |
if(divisor > 0) { | |
cont = false; | |
} | |
} | |
System.out.println("GCD of " + dividend + " and " + divisor + " is " + gcd() + "."); | |
} | |
// method for computer gcd | |
public static int gcd() { | |
while (divisor != 0) { | |
int temp = divisor; | |
divisor = dividend % divisor; | |
dividend = temp; | |
gcd = dividend; | |
} | |
return gcd; | |
} | |
// method for checking the right type (int) | |
public static void checkType(Scanner scan) { | |
while (true) { | |
if(scan.hasNextInt()) { | |
break; | |
} else { | |
System.out.print("Please enter a positive 'integer': "); | |
scan.next(); | |
continue; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment