-1

我需要复习一下将类从一个文件移动到两个文件。我的示例代码在一个名为“ external_class_file_main ”的文件中。程序运行良好,代码如下所示:

Public class external_class_file_main {

    public static int get_a_random_number (int min, int max) {
        int n;
        n = (int)(Math.random() * (max - min +1)) + min;
        return (n);

    }

    public static void main(String[] args) {
        int r;
        System.out.println("Program starting...");

        r = get_a_random_number (1, 5);
        System.out.println("random number = " + r);

        System.out.println("Program ending...");

    }

}

我将get_a_random_number类移动到一个名为“ external_class_file ”的单独文件中。当我这样做时,我收到以下错误:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
The method get_a_random_number(int, int) is undefined for the type
external_class_file_main
at external_class_file_main.main(external_class_file_main.java:20)

external_class_file_main ” 现在包含:

public class external_class_file_main {

    public static void main(String[] args) {
        int r;
        System.out.println("Program starting...");

        r = get_a_random_number (1, 5);
        System.out.println("random number = " + r);

        System.out.println("Program ending...");

    }

}

external_class_file ”现在包含:

public class external_class_file {

    public static int get_a_random_number (int min, int max) {
        int n;
        n = (int)(Math.random() * (max - min +1)) + min;
        return (n);

    }

}
4

3 回答 3

3

您需要get_a_random_number通过类引用 t external_class_file。例如:

int r;
System.out.println("Program starting...");
r = external_class_file.get_a_random_number (1, 5);

不过,您绝对应该遵守 Java 命名约定。

于 2012-12-04T16:59:49.227 回答
1

您不再可以从 external_class_file_main 类访问 get_a_random_number 方法。由于您需要的方法是静态的,您可以直接引用它,如下所示:

public static void main(String[] args) {

    int r;
    System.out.println("Program starting...");

    r = external_class_file.get_a_random_number (1, 5);
    System.out.println("random number = " + r);

    System.out.println("Program ending...");

}

PS,如果您对方法和类使用正确的 Java 命名约定,例如没有下划线并以大写字母开头类,您会发现编码和阅读您的问题的人会容易得多。http://en.wikipedia.org/wiki/Naming_convention_%28programming%29

于 2012-12-04T16:59:00.467 回答
1

这里的解决方案:

public class external_class_file_main {

    public static void main(String[] args) {
        int r;
        System.out.println("Program starting...");

        r = external_class_file.get_a_random_number (1, 5);
        System.out.println("random number = " + r);

        System.out.println("Program ending...");

    }

}

但是,请看一下 Java 命名约定。

于 2012-12-04T17:01:08.283 回答