這次作業主要是請玩家輸入兩個數字,然後求這兩個入字的最大公因數。
// import class
import java.util.Scanner;
public class CH04PR43
{
public static void main(String[] args)
{
// Welcome the user to come to the program
System.out.println("Greatest Common Divisor Finder");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
// Get numbers from the user
System.out.print("Enter first number: ");
int firstNumber = sc.nextInt();
System.out.print("Enter second number: ");
int secondNumber = sc.nextInt();
// do algorithm
int temp = 0;
while (secondNumber!=0)
{
temp = firstNumber % secondNumber;
firstNumber = secondNumber;
secondNumber = temp;
}
System.out.println("Greatest Common Divisor: " + firstNumber);
System.out.println();
// see if the user want to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
}
}
}
No comments:
Post a Comment