Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to get the Greatest Common Divisor between two numbers?

843789Jul 22 2010 — edited Jul 23 2010
This is what I am trying to do: https://docs.google.com/fileview?id=0BzufPKSNRUnSOGE5ODI5ZmEtZWE4ZS00ZTZiLTk3ODItOWFjNjk3MmRiOGZl&hl=en.
I'm trying to get the GCD of any two numbers that the user inputs, but when I input two numbers, nothing happens in my program.

I think I messed up in my 'if' statements. Is it allowed to put a "do-while" loop in an if statement? If not, is there another way to find the GCD?
Please help me fix my code. Here is my code:

import java.util.Scanner;

public class GCD
{
public static void main(String[] args)
{
System.out.println("Greatest Common Divisor Finder");
System.out.println();
String choice = "y";
Scanner sc = new Scanner(System.in);
while (choice.equalsIgnoreCase("y"))
{
System.out.print("Enter first number: ");
double first;
first = sc.nextDouble();
System.out.print("Enter second number: ");
double second;
second = sc.nextDouble();
if (first>second)
{
int subtract;
do
{
subtract = (int)first- (int)second;
}
while (first>second);
int gcd;
gcd = (int)second - subtract;
System.out.println("Greatest Common Divisor: " + gcd);
}
else
{
int subtract;
do
{
subtract = (int)second - (int)first;
}
while(second>first);
int gcd;
gcd = (int)first - subtract;
System.out.println("Greatest Common Divisor: " + gcd);
}
System.out.println();
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}
}

Thank you so much for the help!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 20 2010
Added on Jul 22 2010
11 comments
429 views