Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a complete program that accepts two numbers from the user and then prints

ID: 3645746 • Letter: W

Question

Write a complete program that accepts two numbers from the user and then prints the gcd of the
two numbers. Your program must:

1. Have a method named gcd that accepts two integers as parameters and returns the
greatest common divisor of the two numbers. The greatest common divisor (GCD) of two
integers a and b is the largest integer that is a factor of both a and b. The GCD of any
number and 1 is 1, and the GCD of any number and 0 is that number. For
example: gcd(24, 84) returns 12, gcd(105, 45) returns 15, and gcd(0,8) returns 8.
2. Your program must keep asking the user if she/he has more numbers to find the GCD.
3. Your program must not crash on any input. For example if you ask for an integer value
and the user enters a double or a string your program should not crash, and should keep
asking for the correct input. You must use methods from theScanner class to make your
program robust. The available methods are: hasNextInt(), hasNextDouble(), hasNext()

Here is a sample output
Enter your first number:
werwer
Invalid data, enter a valid integer:
34.45
Invalid data, enter a valid integer:
1we343435
Invalid data, enter a valid integer:
78
Enter your second number:
erer
Invalid data, enter a valid integer:
34.45345
Invalid data, enter a valid integer:
64
The GCD of the numbers 78 and 64 is 2
Do you have more data: yes/no
yes
Enter your first number:
120
Enter your second number:
86
The GCD of the numbers 120 and 86 is 2
Do you have more data: yes/no
yes
Enter your first number:
105
Enter your second number:
45
The GCD of the numbers 105 and 45 is 15
Do you have more data: yes/no
no

Explanation / Answer

I'll get you started: public static void main(String[] args){ Scanner in = new Scanner(System.in); String keepGoing = ""; do{ System.out.println("Enter your first number"); int first = in.nextInt(); System.out.println("Enter your second number"); int second = in.nextInt(); int gcd = gcd(first, second); System.out.println("The GCD of the numbers " + first + " and " + second + " is " + gcd); System.out.println("Do you have more data: yes/no"); keepGoing = in.nextLine(); }while(keepGoing.equals("yes")); } public static int gcd(int first, int second){ int max = Math.max(first, second); int min = Math.min(first, second); if(min == 0) return max; if(min == 1) return 1; int gcd = 0; for(int i=1; i
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote