-1

我无法编译我的代码,特别是在我调用“gcd();”的主程序中 我应该把什么放在括号里?谢谢你。

import java.util.Scanner;

public class gcd {

    public static void main(String[] args) {
        gcd();
    }

    public static int gcd(int a, int b) {
        Scanner console = new Scanner(System.in);
        System.out.println("Please enter the number 1 & 2: ");
        a = console.nextInt();
        b = console.nextInt();
        if (b == 0) 
            return a;
        else return (gcd (b, a % b));
    }
}
4

3 回答 3

4

您的gcd方法需要两个整数参数,因此gcd()不会编译。我认为你应该在这里做的是将 IO 和计算分开 - 也许将 IO 移动到 main 方法:

public static void main(String[] args) {
    Scanner console = new Scanner(System.in);
    System.out.println("Please enter the number 1 & 2: ");
    int a = console.nextInt();
    int b = console.nextInt();
    System.out.println(gcd(a, b));  // notice the two int arguments
}

public static int gcd(int a, int b) {  // no IO, only gcd calculation
    if (b == 0) 
        return a;
    else return (gcd(b, a % b));
}

将您的程序分成“逻辑”组件通常很好。在我上面的内容中,该main方法处理 IO 并gcd处理实际计算。

于 2012-12-03T03:19:44.470 回答
2

括号允许您将数据传递给方法。在这种情况下,您将两个ints 传递给gdc(ab)。

当你定义你的方法时,括号之间和之后的部分public static int gcd是你告诉你的方法应该传递什么变量给它的地方。

于 2012-12-03T03:20:32.570 回答
2

因为 gcd 方法有两个它正在接收的整数值(a 和 b),所以您应该通过传递两个整数值来调用该方法。

例如:gcd(3, 5);

或者您可以传递两个 int 类型的变量。

于 2012-12-03T03:21:17.230 回答