我为Java编程类简介创建了一个用两个数字表示的方法调用程序的GCD。基本上,用户输入两个数字,然后将这些数字发送到我创建的“ gcd”方法,然后它计算这两个数字的GCD,并显示给用户。对于以下代码行,我得到了“非法代码开始”:System.out.println(“ GCD为:” + gcd +);我在下面放置了我的Java代码以供参考,以及有关调试它的帮助,我不确定自己做错了..谢谢!
package gcdfunction;
/**
*
* @
*/
import java.util.Scanner;
public class GcdFunction {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//initializing variables
Scanner input = new Scanner(System.in);
int num1;
int num2;
//Asking user for first number
System.out.print("Enter the first number: ");
//Prompting user input for first number
num1=input.nextInt();
//Asking user for second number
System.out.print("Enter the second number: ");
//Prompting user input for secoond number
num2=input.nextInt();
//calling GCD Method
int gcd = gcd(num1,num2);
//The GCD of the two numbers the user chose displayed to the user
System.out.println("The GCD is: " + gcd +);
}
//GCD Function
public static int gcd(int x, int y){
int num1 = 0;
int num2 = 0;
while(num1 != num2){
while(num1>num2){
num1 = num1 - num2;
}
while(num2 > num1){
num2 = num2 - num1;
}
}
return num1;
}
}
删除main中最后一个println语句中gcd之后的+符号。您的方法gcd也不正确,将始终返回0,因为num1和num2在进入while循环之前被设置为零。我只是将gcd的方法参数名称设置为num1和num2。那会给你你的gcd。我还删除了内部循环,因为您不需要GCD算法的内部循环。
package gcdfunction;
import java.util.Scanner;
public class GcdFunction {
public static void main(String[] args) {
//initializing variables
Scanner input = new Scanner(System.in);
int num1;
int num2;
//Asking user for first number
System.out.print("Enter the first number: ");
//Prompting user input for first number
num1=input.nextInt();
//Asking user for second number
System.out.print("Enter the second number: ");
//Prompting user input for secoond number
num2=input.nextInt();
//calling GCD Method
int gcd = gcd(num1,num2);
//The GCD of the two numbers the user chose displayed to the user
System.out.println("The GCD is: " + gcd);
}
//GCD Function
public static int gcd(int num1, int num2){
while(num1 != num2){
if (num1 > num2){
num1 = num1 - num2;
}
else {
num2 = num2 - num1;
}
}
return num1;
}
}